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.
code:
class Solution {
public:
int lengthOfLongestSubstring(string s)
{
int len_main = 0;
for(int i = 0; i < s.length(); i ++)
{
int len_this = 0;
map<char, int> the_map;
for(int j = i; j < s.length(); j++)
{
if(the_map.count(s.at(j))>0)
{
break;
}
the_map[s.at(j)] = j;
len_this++;
if (len_this > len_main)
{
len_main = len_this;
}
}
}
return len_main;
}
};
comment:
1300 ms | 266.5 MB | Cpp |
It's kinda Enumeration method thus it gets the worst Time-Complexity..
And after I learned some Sliding Window method, I did following solution:
class Solution {
public:
int lengthOfLongestSubstring(string s)
{
unordered_set<char> the_set;
int maxsize = 0;
int left = 0;
for(int i = 0; i<s.length();i++)
{
while(the_set.find(s[i])!=the_set.end())
{
the_set.erase(s[left]);
left++;
}
maxsize = max(maxsize, i-left+1);
the_set.insert(s.at(i));
}
return maxsize;
}
};
comment:
28 ms | 13.2 MB | C++ |
Cuz of Sliding Window do one-layer loop (which avoid nested loop), it just look back to remove the repeated char when a new char on the right come to the unordered_set. It's wiser than the Enumeration method which cause a two-layer nested loop. In other words i can say the time complexity of this operation is big-oh of h where h is n, which the n depends on the input string size.