Sherlock and the Valid String

  • + 0 comments

    Java 8

    public static String isValid(String s) {
            if (s.length()==1)
                return "YES" ;
            // Count the letters 
            int[] l = new int[26] ;
            for (int i=0; i<s.length(); ++i) {
                ++l[s.charAt(i)-97];
            }
            
            // Sort the Letter count
            Arrays.sort(l);
            
            // Check for deviation.
            boolean hasAdjusted = false ;
            int goal = (l[l.length-1]!=l[l.length-2])?l[l.length-2]:l[l.length-1];
            for (int i=l.length-1; i>=0; --i) {
                if (l[i] != 0 ) {
                    if (l[i] > goal) {
                        if (hasAdjusted || l[i] - goal > 1)
                            return "NO";
                        hasAdjusted = true;
                    } else if (l[i] < goal) {
                        if ( hasAdjusted || l[i] != 1)
                            return "NO";
                        hasAdjusted=true;
                    }
                }
            }
            
            return "YES" ;
        }