题目:
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.
解答:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution
{
private:
string s;
public:
Solution(string _s);
int lengthOfLongestSubstring();
};
Solution::Solution(string _s)
{
s = _s;
}
int Solution::lengthOfLongestSubstring()
{
vector<int> dict(256,-1);
int maxlen = 0,start = -1;
for (int i = 0; i != s.length();i++)
{
//当出现重复字符时,dict[s[i]]的值将小于start,此时更新start的值,作为新的字符串开始的计算位置
if (dict[s[i]] > start)
{
start = dict[s[i]];
}
dict[s[i]] = i;
//获取当前位置与start之间的差值,从而计算最大的连续不重复字符的长度
maxlen = max(maxlen,i-start);
}
return maxlen;
}
int main()
{
string a = "abcabcabcdefcdf";
Solution s(a);
int len;
len = s.lengthOfLongestSubstring();
cout<<len<<endl;
return 0;
}
使用类是为了练习c++
以上