Two Characters

  • + 0 comments
    class Result {
    
        /*
         * Complete the 'alternate' function below.
         *
         * The function is expected to return an INTEGER.
         * The function accepts STRING s as parameter.
         */
    
        public static int alternate(String s) {
        // Write your code here
        int[][] countMap = new int[26][26];
        char[][] lastChar = new char[26][26];
        
        int ans = 0;
        
        for (int i = 0; i < s.length(); i++){
            char c = s.charAt(i);
            int index = c - 'a' ;
            for (int j = 0; j < 26; j++){
                if (countMap[index][j] == -1 ){continue;}
                if (lastChar[index][j] == c){
                    countMap[index][j] = -1;
                    countMap[j][index] = -1;
                }
                else{
                    lastChar[index][j] = c;
                    lastChar[j][index] = c;
                    countMap[index][j] += 1;
                    countMap[j][index] += 1;
                }    
            }
        }
        for (int i=0 ; i<26 ; i++){
            for (int j=0 ; j < 26 ; j++) {
                if (i==j){continue;}
                ans = Math.max(countMap[i][j], ans);
            }
        }
        if (s.length() == 1){return 0;}
    
        return ans;
        
        
        }
    }