题很简单,就是求解一个字符串中无重复的最长连续子串。
需要两个指针,一个start_idx:记录当前无重复子串的最左端索引;一个i,记录当前所处的字符索引。
maps记录当前无重复子串中各字符出现的次数,如果maps['a']=1,则表示该子串中a出现过一次。无重复子串即表示maps中所有字符的映射值均<=1。
每次i往右移动一次,当前字符为ch,则maps[ch]++。如果maps[ch]>1,则表示此前ch已经出现过一次,需要将start_idx也开始往右移动,同时将经过的字符从maps清除出去。直到start_idx到达i或者说maps[ch]<=1。
如果maps[ch]=1,那符合条件,此时无重复子串的长度为i - start_idx + 1,和ans取max即可。
AC结果:
Runtime: 20 ms, faster than 65.81% of C++ online submissions for Longest Substring Without Repeating Characters.
Memory Usage: 8.5 MB, less than 66.56% of C++ online submissions for Longest Substring Without Repeating Characters.
#include <iostream>
#include <algorithm>
#include <string.h>
#include <vector>
#include <map>
#include <stdio.h>
using namespace std;
const int maxn = 50000+5;
//char s[maxn];
string s;
int lengthOfLongestSubstring(string s) {
int len = s.length();
if(!len)
return 0;
map<char,int> maps;
maps[s[0]]=1;
int ans = 1;
int start_idx = 0;
for(int i=1;i<len;i++){
maps[s[i]]++;
if(maps[s[i]]>1){
while(start_idx<i && maps[s[i]]>1){
maps[s[start_idx]]--;
start_idx++;
}
}
else{
ans=max(i-start_idx+1, ans);
}
}
return ans;
}
int main()
{
string s = "abcabcbb";
int ans = lengthOfLongestSubstring(s);
cout<<ans<<endl;
return 0;
}