leetcode.3. no repeated character longest substring

I started doing this when the problem is based on the idea before I do, "the longest increasing subsequence" of walking.

Want to open is stored in an array for each character string [No] the beginning of the repeat sequences of length, so that you can find the longest substring of the head, and then press title leetcode.1 idea of ​​the character of add string to do a hash table and check the weight on over.

class Solution {
    public int Check(String s,int i) {
        HashMap<Character, Integer> strLength=new HashMap<>();
        int j=0;
        for(;i<s.length();i++) {
            if(strLength.containsKey(s.charAt(i))) {
                break;
            }
            else {
                strLength.put(s.charAt(i), i);
            }
            j++;
        }
        return j;
    }
    public int lengthOfLongestSubstring(String s) {
        int len[]=new int[s.length()];
        int max=0;
        int index=0;
        for(int i=0;i<s.length();i++) {
            len[i]=Check(s,i);
            if(max<len[i]) {
                index=i;
                max = len [i];
            }
        }
        int lengTh=Check(s,index);
        return lengTh;
        
    }
}

The idea is simple, but .... ran 83ms

So I find a little solution to a problem, learning the "sliding window algorithm."

In fact, that is, add the hash table to check on the weight made some changes. That index is defined at the beginning of a set of elements has been deposited and the end, for example [i, j), and then add the entered key will not be repeated to broaden the boundaries of j, if it is found to be narrowed down is repeated by increasing i, until not repeat so far. Constantly updated with a max [maximum] distance record during the interval. So is the maximum length of the substring of string max after the scan is complete or the whole array obtained.

class Solution {
    public int lengthOfLongestSubstring(String s) {
       int n=s.length();
        int i = 0,j=0;
        int ans=0;
        HashMap<Character, Integer> str=new HashMap<>();
        while(i<n&&j<n) {
            if(!str.containsKey(s.charAt(j))) {
                str.put(s.charAt(j), j-i);
                j++;
                years = Math.max (years j- i);
            }
            else {
                str.remove(s.charAt(i));
                i++;
            }
        }
        return years;
    }
}

 

This ran 13ms, to force wailing.

In fact, this algorithm as well as continue to optimize the space, can be found https://www.codercto.com/a/63236.html

 

Guess you like

Origin www.cnblogs.com/hdrawery/p/12002896.html