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/discuss/6168/my-o-n-solution
下面是我自己的方法,在线AC通过。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int max = 0;
// 记录子串起始位置的前一个位置的下标
// 初始化为-1
int idx = -1;
// 记录字符在s中出现的位置
int locs[256];
memset(locs, -1, sizeof(int) * 256);
for (int i = 0; i < s.size(); i++) {
// 如果s[i]在当前子串中出现过
if (locs[s[i]] > idx) {
// 新子串的起始位置设为s[i]出现的位置+1
// P.S. idx是记录起始位置的前一个位置的下标
idx = locs[s[i]];
}
// 如果当前子串的长度大于最大值
if (i - idx > max) {
max = i - idx;
}
// 更新字符s[i]出现的位置
locs[s[i]] = i;
}
return max;
}
};