3. Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc"
, with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b"
, with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: 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.
my code:
class Solution { public: int lengthOfLongestSubstring(string s) { set<char> seen; int ans = 0; for (int i = 0; i < s.length(); ++i) { int num = 0; for (int j = i; j < s.length(); ++j) { if (seen.count(s[j])) break; seen.insert(s[j]); num++; } seen.clear(); ans = max(num, ans); } return ans; } };
note: Runtime: 316 ms, faster than 5.95% of C++ online submissions for Longest Substring Without Repeating Characters.
effection code:
class Solution { public: int lengthOfLongestSubstring(string s) { if(s.size()<2) return s.size(); int d=1, maxLen=1; unordered_map<char,int> map; map[s[0]]=0; for(int i=1;i<s.size();i++) { if(map.count(s[i])==0 || map[s[i]]<i-d) d++; else d= i- map[s[i]]; map[s[i]]=i; if(d>maxLen) maxLen = d; } return maxLen; } };
Runtime: 40 ms, faster than 24.00% of C++ online submissions for Longest Substring Without Repeating Characters.
第一种方法是最朴素的办法O(N^2),第二种算法比第一种算法,效率高些O(N),再向前查找的时候用map保存了上次出现那个字母的位置,所以,只用线性的时间,就能够查找玩所有的元素。
永远渴望,大智若愚(stay hungry, stay foolish)