题目:
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.
题意:
给定一个字符串,找出字符串中最长的子串的长度,该子串中所有字符不重复。
思路:
依旧使用两个指针,初始化的时候两个指针都指向第一个字符,然后使用表记录所遇到的字符出现的下标,如果第二个指针扫描到字符s[i]已经在表中出现过了,那么记录此时的子串的长度。让第一个指针往前走,走到表中s[i]字符对应的下标。并且第一个指针往前走的过程中,扫描到的字符需要在表中去掉位置信息,相当于“出栈”了,告诉第二个指针这些字符没出现过。
代码如下:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if (s.empty())return 0;
int table[256];
memset(table, -1, sizeof(table));
int first = 0, second = 0, length = s.length();
int m = 0;
while (second < length) {
if (table[s[second]] == -1) {
table[s[second]] = second;
}
else {
m = max(m, second - first);
while (first <= table[s[second]]) {
table[s[first]] = -1;
first++;
}
table[s[second]] = second;
}
second++;
}
m = max(m, second - first);
return m;
}
};