【leetcode】3. Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequence and not a substring.
其实思路还是蛮简单的,首先必须是子串,子串必须连续,连续首先想到的就是字符串扫描,也就是循环。(试图用递归做,比较恶心)
扫描过程中就是收集substr的过程,如果没有重复的字符,就把该字符收进substr,然后和maxlen比较,maxlen记最大的substr长度。
如果出现重复字符,判断是否已经到原来字符串的尾巴,如果到了就返回maxlen,如果没到,就要更新substr,更新substr的过程中先不需要跟maxlen有什么变化。
注意点:
string自己的find函数好像不好用,返回下标,没找到返回std::npos。
string自己的substr函数原型是 substr(int start,int len);
最后用的是stl里的find:Template<T>::iterator find(iterator begin,iterator end,T need);
用的string的构造函数 string(iterator begin,iterator end);
class Solution { public: int lengthOfLongestSubstring(string s) { int len=s.length(); if(len==0||len==1) return len; string substr=""; int maxlen=0; for(int i=0;i<len;i++){ if(find(substr.begin(),substr.end(),s[i])==substr.end()){ substr+=s[i]; if(substr.length()>maxlen) maxlen=substr.length();} else{ auto j=find(substr.begin(),substr.end(),s[i]); if(j==s.end()-1) return maxlen; if(j==substr.end()-1){ substr=""; substr+=s[i];} else { string tmp(j+1,substr.end()); tmp+=s[i]; substr=tmp; } } } if(substr.length()>maxlen) maxlen=substr.length(); return maxlen; } };