问题描述
给定一个字符串s,请你找出其中不含有重复字符的最长字串的长度。
实例:
输入:s="abcabcbb"
输出:3
解释:因为无重复字符的最长字串是“abc”,所以其长度为3;
解题思路
1、遍历字符串查找不含有重复字符的子串
2、比较并记录最长子串长度。
3、当剩余字符不可能构成比当前最长子串更长的子串,则提前结束循环。
解题
类定义,Solution.hpp
#include <string>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s);
};
函数实现,Solution.cpp
#include "Solution.hpp"
int Solution::lengthOfLongestSubstring(string s){
if(s.empty()) return 0;
int startIndex = 0;
int endIndex = 0;
int lastLen = endIndex - startIndex + 1;
do{
for(int i = startIndex; i < endIndex ; i++){
if(s[endIndex] == s[i]){
startIndex = i + 1; //找到当前子串中最后一个与s[endIndex]值相等的字符位置,
//并设置为下一个检查的子串的开始
}
}
int newLen = endIndex - startIndex + 1;
if(newLen > lastLen){
lastLen = newLen;
}
if(lastLen >= s.length() - startIndex){ //已不可能找到比当前最长子串还长的子串了
break;
}
endIndex ++;
}while( endIndex < s.length());
return lastLen;
}
测试
测试代码 main.cpp
#include <iostream>
#include <string>
using namespace std;
#include "Solution.hpp"
void compare_rlt(string &str, int except, int actul)
{
if(except == actul){
cout << str <<" longest substr len is "<< actul <<", succ!" << endl;
} else {
cout << str <<" longest substr len is "<< actul <<", fail!" << endl;
}
}
void test1()
{
Solution s;
string str = "abcaabaeacdace"; //最长是eacd,长度为4.
int len = s.lengthOfLongestSubstring(str);
compare_rlt(str, 4, len);
}
void test2()
{
Solution s;
string str = "abcaabaeadace"; //最长是dace,长度为4.
int len = s.lengthOfLongestSubstring(str);
compare_rlt(str, 4, len);
}
void test3()
{
Solution s;
string str = "abcaabaeadae"; //最长是abc,长度为3.
int len = s.lengthOfLongestSubstring(str);
compare_rlt(str, 3, len);
}
void test4()
{
Solution s;
string str = ""; //字符串长度为0
int len = s.lengthOfLongestSubstring(str);
compare_rlt(str, 0, len);
}
int main()
{
test1();
test2();
test3();
test4();
return 0;
}
编译测试代码
g++ -g main.cpp Solution.cpp
执行结果