Problem:
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.
分析:
使用hashtable解决此问题(代码使用map)。其中键为字符,值为字符位置下标。设置起始位置位begin,每次查看字符c是否存在于map中,且下标是否大于begin(在当前子串范围内)。若是则重复,将begin更新为hashMap[c] + 1(c字符原位置+1)。更新c下标。
AC Code (C++):
class Solution {
public:
//981 / 981 test cases passed.
//Runtime: 99 ms(速度不是很快,不知是不是因为使用了map,亦可不使用map,直接用hash数组)
int lengthOfLongestSubstring(string s) {
map<char, int> hashMap;//键为字符,值为字符所在位置
int maxLength = 0;
int begin = 0;
for (int i = 0; i < s.size(); ++i){
map<char, int>::iterator iter = hashMap.find(s[i]);
if (hashMap.find(s[i]) != hashMap.end() && iter->second >= begin){//在当前范围内重复出现
if (maxLength < i - begin){
maxLength = i - begin;
}
begin = iter->second + 1;
}
hashMap[s[i]] = i;//更新位置
}
if (maxLength < s.size() - begin){
maxLength = s.size() - begin;
}
return maxLength;
}
};
总结:
hashTable的使用