复习了一下STL容器中的map, 才发现map的排序并非按照存储顺序,而是按照它规定的顺序,比如Int类型会按照数值大小,于是需要一个指针保存最大子串的起始位置。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
//利用哈希表保存字符串的元素是否出现,若发现有重复元素,count的值对比之前的值是否是最大,直至循环结束
if(s.empty())
return 0;
unordered_map<char,bool>length_map;
char *p,*q;//p指针指向需要判断是否重复的元素,q指向最长子串的起始位置
p=&s[0];
if(*(p+1)=='\0')
return 1;
int count, max;
count=0;
max=0;
q=&s[0];
while(*p!='\0')
{
if(length_map.empty()||length_map.find(*p)==length_map.end()||length_map[*p]==false)
{
length_map[*p]=true;
count++;
if(count>max)
max=count;
}
else
{
while(*q!=*p)
{
length_map[*q]=false;
count--;
q++;
}
length_map[*q]=false;
count--;
q++;
length_map[*p]=true;
count++;
}
p++;
}
return max;
}
};