第三題:給定一個字符串,請你找出其中不含有重復字符的 最長子串 的長度。


個人解題思路:新建一個子串,原來字符串每個字符和子串比較,如果有相同,子串清空,否則 加入子串

一開始用了迭代器,后期置換迭代器獲得這個,改進空間非常大。
執行用時 :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 ;
}
};

 

網友提交解法,版權屬於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; } };

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM