題目
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
思路
從左向右遍歷字符串並作爲子串,創建一個字典存儲當前子串中各個字符的個數,當判斷當前子串有重複的字符時,子串向右滑動1位,即遍歷開頭的位置加1。以輸入字符串'edvldf'爲例:當遍歷到第2個d時向右滑動1位,從第一個d開始遍歷,並且“被滑掉”的字符的個數要減1,取當前子串的長度(遍歷下標減去開始位置再加1就是)存入結果res中;然後從第一個d開始遍歷又到第二個d時向右滑動1位,從v開始遍歷,以此循環一直到遍歷完整個字符串。最後返回子串長度的最大值。
代碼
Python
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
start = 0
end = 1
res = end - start
count_dic = {}
for letter in s:
count_dic[letter] = count_dic.get(letter,0) + 1#如果字典已經含當前字符則個數加1,否則其個數爲1
while count_dic.get(letter) > 1:
count_dic[s[start]] -= 1
start += 1
res = max(res,end - start)
end += 1
return res
Java
public class Solution {
public int lengthOfLongestSubstring(String s) {
int start = 0;
int end = 1;
int res;
if(s.length() == 0)
return 0;
else
res = end - start;
Map<Character,Integer> map = new HashMap<Character,Integer>();
for(int i = 0;i < s.length();i++)
map.put(s.charAt(i),0);
for(int i = 0;i < s.length();i++)
{
map.put(s.charAt(i),map.get(s.charAt(i)) + 1);
//while循環實現子字符串往右滑動
while(map.get(s.charAt(i)) > 1)
{
map.put(s.charAt(start),map.get(s.charAt(start)) - 1);
start += 1;
}
if(end - start > res)
res = end - start;
end++;
}
return res;
}
}