lc 3 Longest Substring Without Repeating Characters
3 Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Examples:
- Given "abcabcbb", the answer is "abc", which the length is 3.
- Given "bbbbb", the answer is "b", with the length of 1.
- Given "pwwkew", the answer is "wke", with the length of 3. Note that
the answer must be a substring, "pwke" is a subsequence and not a
substring.
动态规划 Accepted##
index数组用来标记该位是否第一次出现,invalid变量用来表示当前研究的子串头部的前一位,length用来表示当前研究的子串的长度。用动态规划的方法可以把时间复杂度降到最低的O(n)。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> index(256, -1);
int length =0;
for (int invalid = 0, i = 0; i < s.length(); i++) {
invalid = max(index[s[i]]+1, invalid);
index[s[i]] = i;
length = max(length, i-invalid+1);
}
return length;
}
};