给定一个字符串 s
,请你找出其中不含有重复字符的 最长子串 的长度。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int * p,*q;
//p=s,q=s;
for(int i=0;i<s.size();i++){
for(int j=i+1;j<s.size();j++){
if(s[j]==s[i])
printf("j%d,%d\n",j,i);
}
}
unordered_set<char> myset;
int right = 0;
int ans = 0;
for (int left = 0; left < s.size(); left++) {
while (right < s.size() && !myset.count(s[right])) {
myset.insert(s[right]);
right++;
}
if (myset.size() > ans) ans = myset.size();
myset.erase(s[left]);
}
return ans;
//return 1;
}
};
第二版
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int * p,*q;
//p=s,q=s;
for(int i=0;i<s.size();i++){
for(int j=i+1;j<s.size();j++){
//if(s[j]==s[i])
//printf("j%d,%d\n",j,i);
}
}
unordered_set<char> myset;
int right = 0;
int ans = 0;
for (int left = 0; left < s.size(); left++) {
while (right < s.size() && !myset.count(s[right])) {
myset.insert(s[right]);
right++;
}
if (myset.size() > ans) ans = myset.size();
std::unordered_set<char>::iterator it;
std::cout << "myset" << ": ";
for ( it = myset.begin(); it != myset.end(); it++ )
std::cout << *it << " ";
std::cout << std::endl;
myset.erase(s[left]);
for ( it = myset.begin(); it != myset.end(); it++ )
std::cout << *it << " ";
std::cout << std::endl;
}
return ans;
//return 1;
}
};