个人解题思路: 新建一个子串, 原来字符串每个字符和子串比较, 如果有相同, 子串清空, 否则 加入子串
一开始用了迭代器, 后期置换迭代器获得这个, 改进空间非常大.
执行用时 :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;
- }
- };
来源: http://www.bubuko.com/infodetail-3279870.html