LeetCode 3. Longest Substring Without Repeating Characters
Solution1:我的答案
该方法中哈希表记录的是字符出现的次数。标准的贪心算法,超过80%的答案;
如果哈希表记录字符出现的位置则还能进一步优化。
class Solution {
public:
int lengthOfLongestSubstring(string s) { //我猜是贪心算法
int n = s.size();
if (n <= 1) return n;
int start = 0, i = 0, max_len = 0, hash[256] = {0};
while (i < n && start < n) {
hash[s[i]]++;
if (hash[s[i]] <= 1) { //继续向后走
max_len = max(max_len, i - start + 1);
} else { //得更新一波起点
int k = start;
for (; k <= i; k++) {
hash[s[k]]--;
if (s[k] == s[i])
break;
}
start = k + 1;
max_len = max(max_len, i - start + 1);
}
i++;
}
return max_len;
}
};
Solution2
参考链接:http://www.cnblogs.com/grandyang/p/4480780.html
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int m[256] = {0}, res = 0, left = 0;
for (int i = 0; i < s.size(); ++i) {
if (m[s[i]] == 0 || m[s[i]] < left) {
res = max(res, i - left + 1);
} else {
left = m[s[i]];
}
m[s[i]] = i + 1;
}
return res;
}
};