Share 5ms Java Recursion Solution


  • 0
    W
    public int longestSubstring(String s, int k) {
        if(s.length() == 0) return 0;
        int[] counter = new int[26];
        boolean flag = false;
        char[] ss = s.toCharArray();
        for(int i = 0; i < ss.length; i++) {
            counter[ss[i]-'a']++;
        }
        HashSet<Character> set = new HashSet<Character>();
        
        for(int i = 0; i < 26; i++) {
            if(counter[i] > 0 && counter[i] < k) {
                flag = true;
                set.add((char)('a'+i));
            }
        }
        if(!flag) return ss.length;
        int start = 0;
        int res = 0;
        for(int i = 0; i < ss.length; i++) {
            if(set.contains(ss[i])) {
                res = Math.max(res, longestSubstring(s.substring(start, i), k));
                start = i+1;
            }
        }
        res = Math.max(res, longestSubstring(s.substring(start), k));
        return res;
    }

Log in to reply
 

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