leetcode 3. 无重复字符的最长子串
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
方法1
暴力求解O(n^2)时间复杂度。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int ans = 0,i,j,k = s.size();
set<char> se;
for(i = 0;i < k;++i){
se.clear();
for(j = i;j < k;++j)
if(se.count(s[j]))
break;
else
se.insert(s[j]);
ans = ans > j - i ? ans : j - i;
}
return ans;
}
};
方法2
应用mp求解O(nlogn)时间复杂度。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int ans = 0,start = 1,end = 1;
map<char,int> mp; //存储每个字符目前为止最后一次出现的位置
int len = s.size();
s = " " + s; //让题目所给字符串下标从1开始,以便mp存储
for(;end <= len;++end)
if(mp[s[end]] == 0) //如果未出现过,就直接标记
mp[s[end]] = end;
else //出现过就更新ans和start
ans = ans > (end - start) ? ans : (end - start),
start = start > mp[s[end]] + 1 ? start : mp[s[end]] + 1,mp[s[end]] = end;
ans = ans > (end - start) ? ans : (end - start);
return ans;
}
};