这题不算难,但是很多边边角角需要考虑。短时间内写出bug-free的代码我觉得不容易。
需要注意:
1) 用双指针+map就可以了。时间复杂度O(n)。
2) 注意m[ch]记录的是字符ch的位置。如果以前有冲突的话,m[ch]要更新。
3) 返回maxLen。当位置j的ch与前面的ch有重复,但前面的ch已经<i,则不用考虑。case "tmmzuxt"。
4) 当j到达末端时, 若无冲突,需要考虑是否更新maxLen。case "aab"。
5) 不管是否有冲突, m[ch]都要更新。
#include <iostream>
#include <string>
#include <map>
using namespace std;
int lengthOfLongestSubstring(string s) {
size_t i=0, j=0;
map<char, int> m;
size_t s_len=s.size();
size_t maxLen=0;
//string ret_str; //for debug
while((i < s_len) && (j<s_len)) {
char ch = s.at(j);
if ((m.count(ch)==0) || (m[ch]<i)) { //m[ch]<i is for the case "tmmzuxt"
if (j==s_len-1) maxLen=max(maxLen, j-i+1); //for the case "aab"
}else {
if (maxLen < j-i) {
maxLen = j-i;
// ret_str = s.substr(i, j-i); //for debug
}
i=m[ch]+1; //due to conflict, move i to the first place of conflict plus 1.
}
m[ch]=j++;
}
return (int)maxLen;
}
int main()
{
string s1="au";
string s2="pwwkew";
string s3="";
string s4="babcda";
string s5="abcabcbb";
string s6= "aab";
string s7="nfpdmpi";
string s8="tmmzuxt";
cout<<lengthOfLongestSubstring(s1);
cout<<lengthOfLongestSubstring(s2);
cout<<lengthOfLongestSubstring(s3);
cout<<lengthOfLongestSubstring(s4);
cout<<lengthOfLongestSubstring(s5);
cout<<lengthOfLongestSubstring(s6);
cout<<lengthOfLongestSubstring(s7);
cout<<lengthOfLongestSubstring(s8);
return 0;
}