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.
这道题花了比较长的时间。
如果用 n2 的时间复杂度则很好处理,只要遍历即可。但是用 n的时间复杂度完全可以完成。
用n的时间扫描s,能够获得s中字符的信息。使vec的对应位置指向该字符的前一个位置。
然后维护两个指针 first和i
i从头遍历,first则是限定不重复字符串的边界。
代码些麻烦了,如果直接从动态窗口考虑代码会好写的多。什么问题都想建个索引都养成习惯了……
class Solution { public: int lengthOfLongestSubstring(string s) { if(s == "")return 0; map<char , vector<int>> m; int last = 0; for(int i = 0 ; i < s.length() ;i++) { char temp = s[i]; m[temp].push_back(i); } vector <int>vec(s.length(),0); map<char ,vector<int>> ::iterator iter; for(iter = m.begin() ; iter != m.end();iter++) { vector<int> vtmp(iter->second); vec[vtmp[0]] = -1; if(vtmp.size() - 2 == 0&&vtmp[0] > last) last = vtmp[0]; for(int i = 1 ; i < vtmp.size() ;i++) { vec[vtmp[i]] = vtmp[i-1]; if(i == vtmp.size() - 2) { if(vtmp[i] > last) last = vtmp[i]; } } } int first = 0 , longest = 1 ; for(int i = 0; i < s.length() ;i++) { if(vec[i] < first) { int tp = i - first +1; longest = longest > tp ? longest : tp; } else { first = vec[i]+1; int tp = i - first +1; longest = longest > tp ? longest : tp; } } int l2 = s.length()-last -1; return longest > l2 ? longest : l2; } };