1 题目简述
Given a string, find the length of the longest substring withoutrepeating characters.
给定一个字符串,找到最长的没有重复字符的子串。
Examples:
Given "abcabcbb"
, theanswer is "abc"
, which the lengthis 3.
给定字符串 "abcabcbb"
,答案为长度为3的子串"abc"
。
Given "bbbbb"
, theanswer is "b"
, with the lengthof 1.
给定字符串 "bbbbb"
,答案为长度为1的子串"b"
。
Given "pwwkew"
, theanswer is "wke"
, with the lengthof 3. Note that the answer must be a substring, "pwke"
is a subsequence and not a substring.
给定字符串 "pwwkew"
,答案为长度为3的子串"wke"
。注意,答案必须是一个子字符串, "pwke"
是一个子序列而不是一个子字符串。
2 答案详解
(1) 解决思想
首先,从头开始遍历给定的字符串,找出第一个不含重复字符的子串。例如:给定的字符串为:abcabcd,找到第一个不含重复字符的子串为abc,并将该子串的首字符下标记为pos(此时pos为0),且将该子串的长度记为max_size(此时max_size为3)。
然后,此时遍历到字符串的第4个字符(a),该字符的上个子串(abc)中含有的字符,故调整遍历范围,从上个子串中重复字符的下一个字符(下标为2)开始遍历,找出下一个不含重复字符的子串。此时找到的子串为bca,但由于该子串的长度<=上个子串的长度,故不需要更新pos和max_size。
之后,以此类推,找到最长的不含重复字符的子串abcd,更新pos为3,更新max_size为4。
最后,将给定字符串从pos位置开始,共max_size个字符构造一个字符串string(str,pos,max_size),其中str为给定字符串,并将其返回。
(2) 设计程序
所设计的程序采用类模板实现,程序如下:
#include
#include
using std::cout;
using std::endl;
using std::string;
template
class Solution
{
private:
T str;
public:
Solution(const T& s):str(s) {}
T LongestSubstring();
};
template
T Solution::LongestSubstring()
{
if(str.size() < 2) {
return str;
}
int i,j,k(0);
int pos(0);
int max_size(0);
for(i = 1; i < str.size(); i++) {
j = k;
while(j < i and str[j] != str[i]) {
j++;
}
if(j < i and max_size < i-k ) {
max_size = i -k;
pos = k;
k = j + 1;
i = k;
} else if(j == k) {
j++;
k++;
}
}
if(max_size < i -k) {
pos = k;
max_size = i -k;
}
return T(str,pos,max_size);
}
int main()
{
const string str1 = "pwwkew";
const string str2 = "bbbbbb";
const string str3 = "abcdef";
Solution sol1(str1);
Solution sol2(str2);
Solution sol3(str3);
cout << "The string:" << str1 << ",the longest substring:"<< sol1.LongestSubstring() << endl;
cout << "The string:" << str2 << ",the longest substring:"<< sol2.LongestSubstring() << endl;
cout << "The string:" << str3 << ",the longest substring:"<< sol3.LongestSubstring() << endl;
}
程序运行结果为:
The string:pwwkew,the longest substring:wke
The string:bbbbbb,the longest substring:b
The string:abcdef,the longest substring:abcdef