Longest Substring Without Repeating Characters
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
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.
Input: s = ""
Output: 0
class Solution { public: int lengthOfLongestSubstring(string s) { vector<int> dict(256,-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; } };
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; } };
题目地址