Given a string, find the length of the longest substring without repeating characters.
Examples:
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.
大致意思就是给个字符串,求出最长的无重复字母的子串长度(注意是子串,连续,子序列可以不连续)
下给出自己过的代码,命名不太规范有点丑,听说还有用哈希的不过刚学C++太菜了啥都不会,如果有以后补。
#include<cstring>
#include<algorithm>
#include<string>
bool IsRep(string s);
class Solution {
public:
int lengthOfLongestSubstring(string s)
{
if (s.length() == 0) return 0;
int ans=1,j=2;
for(int i=0;i<s.size()-1;i++)
{
while(j<=s.size()-i)
{
if(!IsRep(s.substr(i,j)))//i从0开始即从第一个字符开始找无重复子串,j是长度
{
j++;//没重复的j就加1
if(j==s.size()+1-i)//取的子串到字符串末尾了后面就不用看了肯定比这个短
{
ans=std::max(ans,j-1);
return ans;
}
}
else//有重复了,表面这是以s[i]开头的最长无重复子串了,break掉
{
ans=std::max(ans,j-1);
break;
}
}
}
return ans;
}
};
bool IsRep(string s)//判断是否有重复字符
{
int IsReps[255];
for (int i = 0; i < 255; i++)
IsReps[i] = 0;
for (int i = 0; i<s.size(); i++)
{
int a = s[i];
IsReps[a]++;
if (IsReps[a]>1)
{
return true;
}
}
return false;
}
看起来复杂度比较高,但有杂七杂八的剪枝后大概不会很慢,比如如果以s[i]开头的满足要求子串长度是10,那么检测以s[i+1]开头的满足要求最长子串时,就可以直接从长度为11开始,不符合要求直接break。