Question:
Longest Substring Without Repeating Characters
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Example 4:
Input: s = ""
Output: 0
Solution 1:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> dict(256,-1); //用Ascll码来作为key, 该位无值事默认为-1
int maxLen = 0, start = -1;
for(int i = 0; i != s.length(); i++){
if(dict[s[i]] > start)
start = dict[s[i]];
dict[s[i]] = i;
maxLen = max(maxLen, i-start);
}
return maxLen;
}
};
Solution 2: 思路类似。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int maxLen = 0, start = -1;
unordered_map <char, int> hashMap;
for(int i = 0; i < s.length(); i++)
{
if (hashMap.find(s[i]) != hashMap.end())
{
start = hashMap[s[i]] > start? hashMap[s[i]]:start;
}
hashMap[s[i]] = i;
maxLen = max(maxLen, i - start);
}
return maxLen;
}
};