题目链接:https://leetcode.com/problems/longest-substring-without-repeating-characters/#/description
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.
解题思路:其实看到题后并没有想到特别好的思路,最先想到的是动态规划,从头开始遍历记录每个位置的最长不重复子串,判断有没有重复的我也能想到用类似map之类的,但是如果遇到重复的需要更新最长子串,还需要重新定位子串开始的位置,这个怎么做我就想不到什么好办法了。然后就放弃了,去看Discuss了。。。看了大佬的解法,顿悟>_<
重点还是在于判断是否有重复的以及如何重定位开始位置,大佬的映射是从字符到这个子串中该字符的位置,如果查到一个位置比子串开始的位置还要大,就说明这个字符已经出现过了,那么就把开始位置更新到上次出现这个字符的位置后。废话不多说,上代码。
int lengthOfLongestSubstring(string s) {
vector<int> strMap(150, -1);
int maxlen = 0, start = -1;
for(int i = 0; i != s.length(); ++i){
if(strMap[s[i]] > start){
start = strMap[s[i]];
}
strMap[s[i]] = i;
maxlen = max(maxlen, i-start);
}
return maxlen;
}