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.
思路:一遍遍历一边记录最大长度。如果出现重复字符,则从当前不重复的cursub string中截取重复位置之后的substr,并与重复字母拼接成新的cursub,判断新的cursub长度是否超过当前所知的最长。
复杂度分析:O(n) ,我的解法38ms,但leetcode有更快!待我研究下
开心的是又一次 bug free!
总结:3种解法:(1)string (2)two pointer (3)hashtable! 哇这么多方法。
class Solution { public: int lengthOfLongestSubstring(string s) { //check validation if(s.empty()) return 0; //check specail case or bound; int len=s.length(); if(len==1) return 1; //general case string cursub; cursub=s[0]; int lmax=1; int lcur=1; for(int i=1;i<len;i++){ int pos=cursub.find(s[i]); if(pos>=0){ if(pos+1==lcur) cursub.clear(); else cursub = cursub.substr(pos+1,cursub.length()-pos); } cursub+=s[i]; lcur=cursub.length(); if(lcur>lmax) lmax=lcur; } return lmax; } };