(UVA) Scrolling Sign - Solution

Link to the problem: https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=2623

Some comments can be found in the code below.


import java.io.*;
import java.util.*;

class Main {
    public void process() throws NumberFormatException, IOException {
        Scanner sc = new Scanner(System.in);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        int numTests = sc.nextInt();
        for (int test = 0; test < numTests; test++) {
            int numCharactersOnSign = sc.nextInt();
            int numWords = sc.nextInt();
            String[] words = new String[numWords];
            for (int i = 0; i < numWords; i++) {
                words[i] = sc.next();
            }
           
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < words.length; i++) {
                int start = 0;
                for (int j = sb.length()-1; j >= Math.max(0, sb.length()-numCharactersOnSign); j--) {
                    // if it does not match, and there is no chance that the new word matches somehow with the previous word
                    if (words[i].charAt(0) != sb.charAt(j) && sb.length()-j >= words[i].length()) {
                        break;
                    }
                    // if the first character of the new word matches with a character of the previous word, I check the next characters
                    if (words[i].charAt(0) == sb.charAt(j)) {
                        boolean possible = true;
                        int l = 1;
                        for (int k = j+1; k < sb.length() && l < words[i].length(); k++, l++) {
                            if (words[i].charAt(l) != sb.charAt(k)) { // if the sequence does not match
                                possible = false;
                            }
                        }
                        if (possible) { // if the sequence matches, I do not need some first characters of the new word
                            start = l;
                        }
                    }
                }
                sb.append(words[i].substring(start, words[i].length()));
            }
           
            bw.write(sb.length()+"\n");
        }
                                              
        bw.flush();
        bw.close();
       
        return;
    }
   
    public static void main(String[] args) throws NumberFormatException, IOException {
        Main m = new Main();
        m.process();
       
        System.exit(0);
    }
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução