问题描述
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,记录每个字符出现的位置。如果字符出现过,就将慢指针移动到重复出现的字符的下一个位置,不断计算此时不重复字符串的长度,直到循环结束。
代码
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if (s.length() < 2)
return s.length();
int length = 0;
unordered_map<char, int> map;
for (int i = 0, j = 0; i < s.length(); i++){
if (map[s[i]] != 0){
j = max(j, map[s[i]]);
}
map[s[i]] = i+1;
length = max(length, i - j + 1);
}
return length;
}
};
时间复杂度:
O(n)
空间复杂度:
O(n)
反思
一开始设置的判断字符是否出现的条件又问题,因为map的默认值是0,而第一个字符的位置也是0,导致这个字符第一次出现被认为是没有出现。就乱套了。
解决方法是直接记录重复应该进入的下一个字符的index,就可以记录第一个字符了。
这个时候java的优势就体现出来了,用更多的方法来更明确的解决问题。