3. Longest Substring Without Repeating Characters
一、问题描述
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.
三、解题思路
Set
- 判断是否出现重复,可以考虑使用set 集合来做。因为集合中的值是不允许重复的。首先遍历一遍string 添加到一个set中,set的大小,即时不重复子串的最大长度。
- 然后依次判断以 i 开头的不重复子串的长度是多少,并不断更新最大值,如果最大值达到了上面求出的最大子串的长度,那么就直接返回。在计算以 i 开头的子串长度时,遇到重复的直接返回,否则长度加一并继续遍历。
- 这个算法不是那么棒呦,复杂度应该是O(n2)
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if(s.size() == 0)return 0;
if(s.size() == 1)return 1;
int max = 0;
set<char> tot;
for (int i = 0, n = s.size(); i < n; ++i) {
tot.insert(s[i]);
}
for (int i = 0, n = s.size(); i < n; ++i) {
set<char> cache;
cache.insert(s[i]);
int count = 1;
for (int j = i+1; j < n; ++j) {
if(cache.find(s[j]) == cache.end()){
cache.insert(s[j]);
count++;
}else{
break;
}
}
if(count > max)max = count;
if(max == tot.size())break;
}
return max;
}
};