来源:Leetcode
原帖:http://oj.leetcode.com/problems/longest-substring-without-repeating-characters/
题目:
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.
Solution: Pay attention when moving the 'start' pointer forward.
代码:
原帖:http://oj.leetcode.com/problems/longest-substring-without-repeating-characters/
题目:
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.
Solution: Pay attention when moving the 'start' pointer forward.
代码:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int res = 0;
int start = 0, end = 0;
int N = s.size();
vector<bool> found(256, false);
while (end < N) { // slinding window (2 pointers)
if (!found[s[end]]) {
found[s[end++]] = true;
continue;
}
res = max(end - start, res);
while (found[s[end]]) {
found[s[start++]] = false;
}
}
res = max(res, end - start);
return res;
}
};
No comments:
Post a Comment