首页 > 代码库 > 3. Longest Substring Without Repeating Characters

3. Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.

Examples:

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

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

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.

 思路:滑动窗口。用map记录char和index,如果碰到相同的char,则将窗口向右滑动。注意 initial=Math.max(res.get(s.charAt(i))+1,initial);,滑动的时候注意如果碰到的重复字母在窗口的左边则不滑动。

public class Solution {    public int lengthOfLongestSubstring(String s) {    if(s.length()==0){        return 0;    }    if(s.length()==1){        return 1;    }    int longest=0;    int initial=0;    Map<Character,Integer> res=new HashMap<>();    for(int i=0;i<s.length();i++){        if(res.containsKey(s.charAt(i))){            initial=Math.max(res.get(s.charAt(i))+1,initial);        }        res.put(s.charAt(i),i);        longest=Math.max(longest,i-initial+1);    }    return longest;    }}

 

3. Longest Substring Without Repeating Characters