We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
I was considering the same thing but thought I was crazy. Here's a Java example for anyone who is curious for the actual algorithm. I believe it's technically O(n) time and O(1) space. Although there are many loops and 2D arrays, they involve the 26 alphabet-size constant.
public static int longestAltString(String s) {
char [][] letters = new char[26][26];
int [][] values = new int[26][26];
for(char c : s.toCharArray()) {
int index = (int)(c - 'a');
for(int i = 0; i < 26; i++) {
if(letters[index][i] != c && values[index][i] != -1) {
letters[index][i] = c;
++values[index][i];
} else {
values[index][i] = -1;
}
if(letters[i][index] != c && values[i][index] != -1) {
letters[i][index] = c;
++values[i][index];
} else {
values[i][index] = -1;
}
}
}
int largestString = 0;
for(int i = 0; i < 26; i++) {
for(int j = 0; j < 26; j++) {
if(values[i][j] > largestString) {
largestString = values[i][j];
}
}
}
if(largestString > 1) {
return largestString;
} else {
return 0;
}
}
Two Characters
You are viewing a single comment's thread. Return to all comments →
I was considering the same thing but thought I was crazy. Here's a Java example for anyone who is curious for the actual algorithm. I believe it's technically O(n) time and O(1) space. Although there are many loops and 2D arrays, they involve the 26 alphabet-size constant.