Sherlock and the Valid String

  • + 0 comments
    public static String isValid(String s) {
            // Write your code here
            HashSet <Character> stringSet = new HashSet<>();
            List <Character> stringList = new ArrayList<>();
            HashMap <Character, Integer> frequency = new HashMap<>();
            HashMap <Integer, Integer> freqCount = new HashMap<>();
            for (char c : s.toCharArray()) {
                stringSet.add(c);
                stringList.add(c);
            }
            for (Character ch : stringSet) {
                frequency.put(ch, Collections.frequency(stringList, ch));
            }
            int size = new HashSet<>(frequency.values()).size();
            if (size == 1) {
                return "YES";
            } 
            for (Integer value : frequency.values()) {
                freqCount.put(value, freqCount.getOrDefault(value, 0) + 1);
            }
            if (freqCount.size() == 2) {
                if (Collections.min(freqCount.keySet()) == 1 && freqCount.get(Collections.min(freqCount.keySet())) == 1) {
                    return "YES";
                } else if (Collections.max(freqCount.keySet())-Collections.min(freqCount.keySet())==1 && freqCount.get(Collections.max(freqCount.keySet())) == 1) {
                    return "YES";
                } else {
                    return "NO";
                }
            }
            return "NO";
        }