My Java Solution From Window

  • 0
    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) {
                return s.length();
                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++;
                        minLen = (pos==start) ? 0 : (pos-start+1);
                        end = pos;
                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.