My Java Solution From Window


  • 0
    Y
    1. scan char array from left to right
    2. if we get a new character, count++, if a character already has nums k. count--
    3. if we get a substring is satisfied with the question, and the start pos from 0, we change next loop's start pos from i+1 to end+1
    4. loop
    public class Solution {
        public int longestSubstring(String s, int k) {
            if(k==1) 
                return s.length();
            if(s.length()<k)
                return 0;
            char[] c = s.toCharArray();
            int res = 0;
            for(int i=0; i<c.length; i++){
                int start=i, end=0, count=0, minLen=0;
                Map<Character, Integer> map = new HashMap<Character, Integer>();
                
                for(int pos=i; pos<c.length; pos++){
                    map.put(c[pos], map.getOrDefault(c[pos], 0)+1);
                    int val = map.get(c[pos]);
                    if(val==k) count--;
                    if(val==1) count++;
                    
                    if(count==0){
                        minLen = (pos==start) ? 0 : (pos-start+1);
                        end = pos;
                    }
                }
                if(minLen!=0)
                    i=end;
                res = Math.max(res, minLen);
            }
            return res;
        }
    }
    

Log in to reply
 

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