个人解题思路:新建一个子串,原来字符串每个字符和子串比较,如果有相同,子串清空,否则 加入子串
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int max = 0 ,count = 0,flag = 0 ;
string news;
// list<char>::iterator list_iter ;
if(s == " ")
max = 1 ;
char *p = (char *)&s[0] ;
while( *p != '\0' )
{
news.push_back(*p);
count++;
if(count > max)
max = count ;
p++;
for(int i = 0 ; i< news.size(); i++)
{
if( news.at(i) == *p)
{
news.clear();
if(count > max)
max = count ;
count = 0 ;
flag++;
p = (char *)&s[flag] ;
break;
}
}
#if 0
//执行用时 :1096 ms, 在所有 cpp 提交中击败了6.52%的用户
//内存消耗 :207.7 MB, 在所有 cpp 提交中击败了7.76%的用户
list_iter = find(news.begin(),news.end(),*p);
if(list_iter == news.end())
{
news.push_back(*p);
count++;
if(count > max)
max = count ;
// cout<<"count"<<count<<endl;
p++;
}
else
{
news.clear();
if(count > max)
max = count ;
// cout<<"max"<<max<<endl ;
count = 0 ;
flag++;
p = (char *)&s[flag] ;
}
#endif
}
//cout<<"max1"<<max<<endl;
return max ;
}
};
网友提交解法,版权属于wangqiim@163.com, 当前学习记录
C++
执行用时 : 16 ms, 在Longest Substring Without Repeating Characters的C++提交中击败了99.48% 的用户
内存消耗 : 9.3 MB, 在Longest Substring Without Repeating Characters的C++提交中击败了87.06% 的用户
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int size,i=0,j,k,max=0;
size = s.size();
for(j = 0;j<size;j++){
for(k = i;k<j;k++)
if(s[k]==s[j]){
i = k+1;
break;
}
if(j-i+1 > max)
max = j-i+1;
}
return max;
}
};