Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Complete the alternate function below.
- static int alternate(String s) {
- String str = removeDuplicates(s);
- if (str.length() < 2) {
- return 0;
- } else {
- boolean[] seen = new boolean[26];
- int bestBet = 0;
- for (int i = 0; i < str.length() - 1; i++) {
- char c1 = str.charAt(i);
- if (seen[(int) c1 - (int) 'a']) {
- str = removeChar(str, c1);
- str = removeDuplicates(str);
- continue;
- }
- for (int j = i + 1; j < str.length(); j++) {
- char c2 = str.charAt(j);
- if (seen[(int) c2 - (int) 'a'] || c1 == c2) {
- str = removeChar(str, c1);
- str = removeDuplicates(str);
- continue;
- }
- seen[(int) c1 - (int) 'a'] = true;
- System.out.println(c1 + " " + c2);
- int candidateLength = 1;
- char currentChar = c1;
- for (int k = j; k < str.length(); k++) {
- if (str.charAt(k) == currentChar) {
- candidateLength = -1;
- break;
- }
- if (currentChar == c1 && str.charAt(k) == c2
- || currentChar == c2 && str.charAt(k) == c1) {
- candidateLength++;
- currentChar = currentChar == c1 ? c2 : c1;
- //System.out.println("currentChar " + currentChar);
- }
- }
- System.out.println(candidateLength);
- if (candidateLength >= bestBet) {
- bestBet = candidateLength;
- }
- }
- }
- System.out.println(bestBet);
- return bestBet;
- }
- }
- static String removeChar(String str, char cToRemove) {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < str.length(); i++) {
- char c = str.charAt(i);
- if (c != cToRemove) {
- sb.append(c);
- }
- }
- return sb.toString();
- }
- static String removeDuplicates(String s) {
- boolean dup = true;
- String str = s;
- while (dup) {
- char cToRemove = '\0';
- dup = false;
- for (int i = 1; i < str.length(); i++) {
- if (str.charAt(i) == str.charAt(i-1)) {
- dup = true;
- cToRemove = str.charAt(i);
- break;
- }
- }
- if (dup) {
- str = removeChar(str, cToRemove);
- System.out.println("remove duplicates result: " + str);
- }
- }
- return str;
- }
Advertisement
Add Comment
Please, Sign In to add comment