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.
<pre name="code" class="cpp">class Solution2 {
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;
}
};
class Solution {
public:
int lengthOfLongestSubstring(string s) {
const int ASCII_MAX = 26;
int last[ASCII_MAX]; // 记录字符上次出现过的位置
int start = 0; // 记录当前子串的起始位置
fill(last, last + ASCII_MAX, -1); // 0 也是有效位置,因此初始化为-1
int max_len = 0;
for (int i = 0; i < s.size(); i++) {
if (last[s[i] - 'a'] >= start) {
max_len = max(i - start, max_len);
start = last[s[i] - 'a'] + 1;
}
last[s[i] - 'a'] = i;
}
return max((int)s.size() - start, max_len); // 别忘了最后一次,例如"abcd"
}
};