|
1 | 1 | package hackerrank; |
2 | | -/* |
3 | | -The characters present in are a, b, e, and f. |
4 | | -This means that must consist of two of those characters and we must delete two others. |
5 | | -Our choices for characters to leave are [a,b], [a,e], [a, f], [b, e], [b, f] and [e, f]. |
6 | | -If we delete e and f, the resulting string is babab. |
7 | | -This is a valid as there are only two distinct characters (a and b), |
8 | | -and they are alternating within the string. |
9 | | -If we delete a and f, the resulting string is bebeeeb. |
10 | | -This is not a valid string because there are consecutive e's present. |
11 | | -Removing them would leave consecutive b's, so this fails to produce a valid string . |
12 | | -Other cases are solved similarly. |
13 | | -babab is the longest string we can create. |
14 | | - */ |
| 2 | + |
15 | 3 | public class TwoCharacters { |
16 | | - static int alternate(String s) { |
17 | 4 |
|
| 5 | + public static final int NUM_LETTERS = 26; |
| 6 | + |
| 7 | + static int alternate(int length, String s) { |
| 8 | + int maxPattern = 0; |
| 9 | + |
| 10 | + if(s.length() == 1)//Edge case where length is 1 |
| 11 | + { |
| 12 | + return maxPattern; |
| 13 | + } |
| 14 | + |
| 15 | + /* Create arrays representing the 26^2 subproblems */ |
| 16 | + int[][] pair = new int[NUM_LETTERS][NUM_LETTERS]; |
| 17 | + int[][] count = new int[NUM_LETTERS][NUM_LETTERS]; |
| 18 | + |
| 19 | + for (int i = 0; i < length; i++) { |
| 20 | + char letter = s.charAt(i); |
| 21 | + int letterNum = letter - 'a'; |
| 22 | + |
| 23 | + /* Update row */ |
| 24 | + for (int col = 0; col < NUM_LETTERS; col++) { |
| 25 | + if (pair[letterNum][col] == letter) { |
| 26 | + count[letterNum][col] = -1; |
| 27 | + } |
| 28 | + if (count[letterNum][col] != -1) { |
| 29 | + pair[letterNum][col] = letter; |
| 30 | + count[letterNum][col]++; |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + /* Update column */ |
| 35 | + for (int row = 0; row < NUM_LETTERS; row++) { |
| 36 | + if (pair[row][letterNum] == letter) { |
| 37 | + count[row][letterNum] = -1; |
| 38 | + } |
| 39 | + if (count[row][letterNum] != -1) { |
| 40 | + pair[row][letterNum] = letter; |
| 41 | + count[row][letterNum]++; |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + /* Find max in "count" array */ |
| 47 | + for (int row = 0; row < NUM_LETTERS; row++) { |
| 48 | + for (int col = 0; col < NUM_LETTERS; col++) { |
| 49 | + maxPattern = Math.max(maxPattern, count[row][col]); |
| 50 | + } |
| 51 | + } |
18 | 52 |
|
| 53 | + return maxPattern; |
19 | 54 | } |
20 | 55 |
|
21 | 56 | public static void main(String[] args) { |
22 | | - System.out.println(alternate("beabeefeab")+", ans: 5"); |
| 57 | + System.out.println(alternate(10, "beabeefeab")+", ans: 5"); |
23 | 58 | } |
24 | 59 | } |
0 commit comments