Sherlock and the Valid String

  • + 0 comments

    import java.io.; import java.math.; import java.security.; import java.text.; import java.util.; import java.util.concurrent.; import java.util.function.; import java.util.regex.; import java.util.stream.*; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList;

    class Result {

    /*
     * Complete the 'isValid' function below.
     *
     * The function is expected to return a STRING.
     * The function accepts STRING s as parameter.
     */
    
    public static String isValid(String s) {
        //Convert to array to get each character
      char[] charArr =  s.toCharArray();
    
            //create hashmap to store the each letters and theri count
    java.util.Map<Character,Integer> charMap = new java.util.HashMap<>();
    for(char c : charArr){
        charMap.put(c, charMap.getOrDefault(c,0)+1);
    }
    
    //Now we want with the same count how many letters are present.
        //So we will get the number of letters with the same count as key and //their count as value
    java.util.Map<Integer,Integer> countMap = new java.util.HashMap<>();
    
    for(int count : charMap.values() ){
        countMap.put(count,countMap.getOrDefault(count, 0)+1 );
    }
    
        //If size is one then all letters have same count
    if(countMap.size()==1){
        return "YES";
    }
    
        //If size is more than 2 then even after removal of one letter it is not //able to get the solution
    if(countMap.size()>2){
        return "NO";
    }
    
    int key1 = (int) countMap.keySet().toArray()[0]; 
        int key2 = (int) countMap.keySet().toArray()[1]; 
    
        int value1 = (int) countMap.values().toArray()[0];
        int value2 = (int) countMap.values().toArray()[1];
    
                //If there is one letter with the one count then we can remove it to //get solution
    
        if ((key1 == 1 && value1 == 1) || (key2 == 1 && value2 == 1)) {
        return "YES";
    }
    

    //To remove one element then count of the number has to be //consecutivem i.e,, key and the number of time it repeated has to be one //i.e., value. if ((key1 + 1 == key2 && value2 == 1) || (key2 + 1 == key1 && value1 == 1)) { return "YES"; } return "NO"; }

    }

        bufferedReader.close();
        bufferedWriter.close();
    }
    

    }