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,否则更新locs数组中的hash值为当前位置。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int loc[256];
memset(loc, -1, sizeof(loc));
int index = -1;
int max = 0;
for(int i = 0; i < s.length(); i++)
{
if(loc[s[i]] > index)
{
index = loc[s[i]];
}
if(i-index>max)
{
max = i-index;
}
loc[s[i]] = i;
}
return max;
}
};
python代码:
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
res = 0
left = 0
d = {}
for i, ch in enumerate(s):
if ch in d and d[ch] >= left:
left = d[ch] + 1
d[ch] = i
res = max(res, i - left + 1)
return res