您的位置:首页 > 其它

Leetcode3. 无重复字符的最长子串

2019-07-15 14:02 549 查看
原文链接:http://www.cnblogs.com/Aiahtwo/p/11188531.html

方法一(自写)暴力法   时间复杂度:O(n^2)

class Solution {
public:
int lengthOfLongestSubstring(string s) {
int count1=0;
for(int i=0;i<s.length();i++)
{
vector<char> v;
int t=0;
v.push_back(s[i]);
t++;
for(int j=i+1;j<s.length();j++)
{

if(count(v.begin(),v.end(),s[j])>0)
break;
else
{
v.push_back(s[j]);
t++;
}
}
if(t>count1)
count1=t;
}
return count1;
}
};

  

方法二:滑动窗口法   时间复杂度:O(2n)

class Solution {
public:
int lengthOfLongestSubstring(string s) {
int i=0,j=0,sum=0;
set<char> num;
while(i<s.length()&&j<s.length())
{
if(num.count(s[j])==0)
{
num.insert(s[j++]);
if(sum<j-i)
sum=j-i;
}
else
num.erase(s[i++]);
}
return sum;
}
};

  

 

转载于:https://www.cnblogs.com/Aiahtwo/p/11188531.html

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: