Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
注意:最后面的子串最长,在循环外也要更新一次最大长度。
C++实现代码如下:
#include#include using namespace std;class Solution{public: int lengthOfLongestSubstring(string s) { if(s.empty()) return 0; if(s.length()==1) return 1; size_t i,j,k=0; //记录最大长度 size_t maxLen=0; //记录最大长度开始的下标 size_t index=0; for(i=1; i maxLen) { maxLen=i-k; index=k; } k=j+1; break; } else j++; } } if(i-k>maxLen) { maxLen=i-k; index=k; } cout<<"index: "< <
#include#include using namespace std;class Solution{public: int lengthOfLongestSubstring(string s) { if(s.empty()) return 0; int maxLen=1; int i,j,k; j=0; k=0; for(i=1; i<(int)s.size(); i++) { j=k; while(j maxLen) maxLen=i-k; k=j+1; break; } } } if(i-k>maxLen) maxLen=i-k; return maxLen; }};int main(){ Solution s; string ss="wlrbbmqbhcdarzowkkyhiddqscdxrjmowfrxsjybldbefsarcbynecdyggxxpklorellnmpapqfwkhopkmco"; cout< <