Recursive solution in java


  • 0
    F
        public int longestSubstring(String s, int k) {
            char[] chars = s.toCharArray();
            HashMap<Character, Integer> hashMap = new HashMap<>();
            for (char aChar : chars) {
                hashMap.put(aChar, hashMap.getOrDefault(aChar, 0) + 1);
            }
            for (Character character : hashMap.keySet()) {
                if (hashMap.get(character) < k) {
                    int result = 0;
                    for (String str : s.split(String.valueOf(character))) {
                        result = Math.max(result, longestSubstring(str, k));
                    }
                    return result;
                }
            }
            return s.length();
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.