Example | Input | Answer |
0 | {"tokyo", "kyoto"} |
1 |
1 | {"aaaaa", "bbbbb"} |
0 |
2 | {"ababab","bababa","aaabbb"} |
1 |
3 | {"eel", "ele", "lee"} |
3 |
4 | {"aaa", "aab", "aba", "abb", "baa", "bab", "bba", "bbb"} |
6 |
5 | {"top","coder"} |
0 |
Example 2:bababa ababab aaabbb ababab aaabbb bababa |
Example 3:ele eel lee eel lee ele |
Example 4:aab aaa aba aaa aba aab abb aaa abb aab abb aba baa aaa baa aab baa aba baa abb bab aaa bab aab bab aba bab abb bab baa bba aaa bba aab bba aba bba abb bba baa bba bab bbb aaa bbb aab bbb aba bbb abb bbb baa bbb bab bbb bba |
Now, given a pair of words, like "tokyo" and "kyoto", how do we determine that they are interesting? One simple way is to break up the first word into every combination of two substrings (which we'll call A and B below), concatenate the substrings in reverse order, and see if they equal the second word. For example:
A | B | B + A | Does it equal "kyoto"? |
t | okyo | okyot | No |
to | kyo | kyoto | Yes |
tok | yo | yotok | No |
toky | o | otoky | No |
To break up strings into substrings, see the substr() method. I provide examples in the string lecture notes for CS140.
In this instance, you are generating all pairs of words of words, and there are (W(W+1))/2 of these. For each pair of words, you are calculating S-1 values of A and B, and the work required to compute A+B is roughly S. Therefore, your program scales with W and S roughly as:
W2S2
With topcoder, the maximum W is 50, and the maximum S is also 50, so the equation above gives you 6,250,000. That's going to be pushing topcoder's time limits, but it is fast enough. Later in the semester, when we study maps, you'll be able to see how to make this program faster.