[Leetcode]Longest Substring Without Repeating Characters

Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.code

Examples:字符串

Given "abcabcbb", the answer is "abc", which the length is 3.get

Given "bbbbb", the answer is "b", with the length of 1.string

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.it

1.解題思路io

本題藉助HashMap實現。
1) 若是字符未出現過,則put(字符,index);
2) 若是字符出現過,則維護len=上次出現的index-遍歷的起始點。
那問題就到了如何去定義遍歷的起始點呢,咱們固然能夠從0開始,而後每次加1,可是經過下面的例子,咱們很容易就發現這樣會有不少狀況冗餘:
「abcdecf」
咱們從index 0開始,到第二個字符c-index5,咱們會發現已經存在,因此len,5-0=5;但若是咱們以後index從1開始,咱們會發現必然還會在index5這邊中止,爲了減小這種冗餘,咱們想到能夠在一次重複後,將start置爲重複元素Index+1,這裏就是index3-d, 這樣咱們在碰到已經存在的字符時,就要再加上一個判斷,看其上一次出現是否在start以前,若是在start以前,則不做考慮,直接Put進新的位置;若是是在start以後,則就代表確實遇到了重複點。
注意點:
1)每次都要更新字符的位置;
2)最後返回時,必定要考慮到從start到s.length(字符串末尾)都沒有遇到重複字符的狀況,所欲須要比較下maxLen和s.length()-start的大小。class

2.代碼遍歷

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if(s.length()==0) return 0;
        HashMap<Character,Integer> hm=new HashMap<Character,Integer>();
        int start=0;
        int maxLen=1;
        for(int i=0;i<s.length();i++){
            if(hm.containsKey(s.charAt(i))&&hm.get(s.charAt(i))>=start){
                int len=i-start;
                maxLen=Math.max(maxLen,len);
                start=hm.get(s.charAt(i))+1;
            }
            hm.put(s.charAt(i),i);
        }
        return Math.max(maxLen,s.length()-start);
    }
}
相關文章
相關標籤/搜索