You are viewing a single comment's thread. Return to all comments →
public static int alternate(String str) { String[] uniqueCharacters = Arrays.stream(str.split("")).collect(Collectors.toSet()).toArray(new String[0]); int maxLength = 0; for(int i=0;i<uniqueCharacters.length-1; i++) { for(int j=i+1; j<uniqueCharacters.length; j++) { String firstChar = uniqueCharacters[i]; String secondChar= uniqueCharacters[j]; String newStr = str; List<String> lst = Arrays.stream(uniqueCharacters).filter(s -> !s.equals(firstChar) && !s.equals(secondChar)).collect(Collectors.toList()); for(String l:lst) { newStr = newStr.replaceAll(l, ""); } if(isAlternateCharacters(newStr) & newStr.length() > maxLength) { maxLength = newStr.length(); } } } return maxLength; } private static boolean isAlternateCharacters(String str) { if(str.length() == 1) return false; char firstchar = str.charAt(0); char secondchar = str.charAt(1); if(firstchar == secondchar) return false; for(int i=0; i<str.length(); i++) { if(i%2 == 0 && str.charAt(i) == firstchar) continue; if(i%2 != 0 && str.charAt(i) == secondchar) continue; return false; } return true; }
Seems like cookies are disabled on this browser, please enable them to open this website
Two Characters
You are viewing a single comment's thread. Return to all comments →