问题:
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
思路:
定义一个数组count,其下标表示字符的ASSIC码,值为该ASSIC码在字符串中出现的位置(位置信息为1,2,3...)
定义一个vector,用来存储每次有字符重复之前的子字符串的长度
定义一个变量begin,用来记录每次非重复子字符串在原字符串中的起始位置,从1开始数
定义一个变量flag,用来记录每次重复的字符,其上一次出现在子字符串中的位置,比如abdrgbs ,那么flag = 2(前一个b出现的位置)
解答:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int count[127] = {0};
vector<int> result;
int index=0;
int k = 1;
int flag=0;
int begin = 1;
for(string::iterator it = s.begin(); it!=s.end(); it++)
{
index = int(*it);
if(count[index]==0 || count[index]<flag) //无重复
{
count[index] = k;
}
else //有重复
{
begin = flag+1;
result.push_back(k-begin);
flag = count[index];
count[index]=k;
}
k++;
}
begin = flag+1;
result.push_back(s.size()-begin+1);
int maxR = 0;
for(vector<int>::iterator it = result.begin(); it!=result.end(); it++)
{
maxR = (maxR>=*it)?maxR:*it;
}
return maxR;
}
};