题目: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.
链接:https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/
描述:找出最长的不重复字母子序列
解法:滑动窗口
solution by python:
class Solution:
# @return an integer
def lengthOfLongestSubstring(self, s):
cdict = {}
ans = 0;beg = 0
for i in range(len(s)):
if s[i] not in cdict:
cdict[s[i]] = i
if i-beg+1 > ans:
ans = i-beg+1
else:
for j in range(beg, cdict[s[i]]):
cdict.pop(s[j])
beg = cdict[s[i]] +1
cdict[s[i]] = i
return ans
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int map[256];
memset(map, -1, sizeof(map));
int beg = 0, ans = 0;
for(int i=0; i<s.size(); i++){
if(map[s[i]] < beg){
map[s[i]] = i;
} else{
ans = max(ans, i-beg);
beg = map[s[i]]+1;
map[s[i]] = i;
}
}
ans = max(ans, int(s.size()-beg));
return ans;
}
};