无重复字符的最长字串(C++,python实现)
C++代码:
#include<iostream>
#include<unordered_set>
#include<string>
using::std::unordered_set;
using::std::string;
using::std::max;
#include<unordered_set>
#include<string>
using::std::unordered_set;
using::std::string;
using::std::max;
class Solution{
public:
unordered_set<char> slen;
int lengthoflongestsubstring(string s)
{
int p=-1,len=0;
int n = s.size();
for(int i=0;i<n;i++)
{
if(i!=0)
{
slen.erase(s[i-1]);
}
while(p+1<n&&!slen.count(s[p+1]))
{
slen.insert(s[p+1]);
p++;
}
len = max(len,p-i+1);
}
std::cout << len << '\n';
return len;
}
};
public:
unordered_set<char> slen;
int lengthoflongestsubstring(string s)
{
int p=-1,len=0;
int n = s.size();
for(int i=0;i<n;i++)
{
if(i!=0)
{
slen.erase(s[i-1]);
}
while(p+1<n&&!slen.count(s[p+1]))
{
slen.insert(s[p+1]);
p++;
}
len = max(len,p-i+1);
}
std::cout << len << '\n';
return len;
}
};
int main()
{
Solution sol;
string s = "abcdefab";
sol.lengthoflongestsubstring(s);
return 0;
}
{
Solution sol;
string s = "abcdefab";
sol.lengthoflongestsubstring(s);
return 0;
}
测试结果:
python代码实现:
class Solution:
def lengthoflongestsubstring(self,s:str):
a = set()
n = len(s)
rk,ans = -1,0
for i in range(n):
if i!=0:
a.remove(s[i-1])
while rk + 1 < n and s[rk+1] not in a:
a.add(s[rk+1])
rk += 1
ans = max(ans,rk-i+1)
print(ans)
return ans
def lengthoflongestsubstring(self,s:str):
a = set()
n = len(s)
rk,ans = -1,0
for i in range(n):
if i!=0:
a.remove(s[i-1])
while rk + 1 < n and s[rk+1] not in a:
a.add(s[rk+1])
rk += 1
ans = max(ans,rk-i+1)
print(ans)
return ans
s = "abcdfea"
foo = Solution()
foo.lengthoflongestsubstring(s)
foo = Solution()
foo.lengthoflongestsubstring(s)
测试结果: