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.
题意:找一个字符串中,没有重复的连续子串的最大长度。
分析:一开始想用 哈希map 来做,发现那样就把自己搞复杂了,哈希不一定非要用map来实现,数组也可以。
其实就是一个对照关系罢了。开一个数组,记录每个字符的最新出现位置,如果有重复,更新左值,并且更新 最大长度即可。
c++ 代码如下:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int maxlen = 0, left = 0;
int size = s.length();
int pre[256];
memset(pre, -1, sizeof(pre));
for(int i = 0; i < size; i++) {
if(pre[s[i]] >= left) {
left = pre[s[i]] + 1;
}
pre[s[i]] = i;
maxlen = max(maxlen, i - left + 1);
}
return maxlen;
}
};