第三题:给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

个人解题思路:新建一个子串,原来字符串每个字符和子串比较,如果有相同,子串清空,否则 加入子串

一开始用了迭代器,后期置换迭代器获得这个,改进空间非常大。
执行用时 :368 ms, 在所有 cpp 提交中击败了10.64%的用户
内存消耗 :9.3 MB, 在所有 cpp 提交中击败了86.76%的用户

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 ;
}
};

网友提交解法,版权属于[email protected], 当前学习记录

 

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; } };

猜你喜欢

转载自www.cnblogs.com/AmyBKLP/p/11826917.html