1.设置开始的窗口长度为1,最大长度为0如果字符串的长度length本身为0返回max_length;
2.将一个字母输入到字符串temp中,如果窗口长度等于length那max_length就等于window_length;
3.判断加入下一个字符后字符串是否重复如果不重复则window_length+1,更新max_length的值和j的值;
4.如果重复则window_length长度不变整体向右移动一个长度,更新j的值;
5.repeat函数判断字符串里是否有重复字符。
#include<iostream>
#include<cstring>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int length = s.length();
int max_length = 0;
int i = 0,j = 0;
string temp,temp1;
if(length == 0)
return max_length;
int window_length = 1;
max_length = 1;
while(j != length - 1)
{
temp = s.substr(i,window_length);
if(window_length == length){
max_length = window_length;
break;
}
if(repeat(s.substr(i,window_length+1))){
window_length++;
if(window_length > max_length)
max_length = window_length;
j = i + window_length - 1;
for (int k = i; k < j; k++) {
cout << s[k];
}
cout << endl;
}
else {
i++;
j = i + window_length -1;
}
}
return max_length;
}
int repeat(string s){
int length = s.length();
int judge = 1;//没有重复
for(int i = 0;i<length;i++){
for(int j = i+1;j<length;j++){
if(s[i] == s[j]){
judge = 0;
break;
}
}
if(judge == 0){
break;
}
}
return judge;
}
};
int main() {
string s1 = "abcabcde";
Solution k;
int g = k.lengthOfLongestSubstring(s1);
cout << "最大长度为" << g;
return 0;
}