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.
STL hash:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char,int> mp;
int lastRepeatPos=-1,k = 0;
for(int i=0; i<s.size();i++)
{
if(mp.find(s[i]) != mp.end() && mp[s[i]]>lastRepeatPos )//重复字符出现,且与之对应的重复字符出现在index之后
{
lastRepeatPos = mp[s[i]];//重复字符出现的位置
}
k = ((i - lastRepeatPos) > k)?(i - lastRepeatPos):k;//i - index期间的字符没有重复的
mp[s[i]] = i;
}
return k;
}
};
64ms
自定义hash
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int m[256];
fill(m, m+256, -1);
int maxLen = 0, lastRepeatPos = -1;
for(int i=0; i<s.size(); i++) {
if (m[s[i]]!=-1 && lastRepeatPos < m[s[i]]) lastRepeatPos = m[s[i]];
if ( i - lastRepeatPos > maxLen ) maxLen = i - lastRepeatPos;
m[s[i]] = i;
}
return maxLen;
}
};
16ms