tip
1.每放进去一个字符,就跟哈希表中已有的字符进行对比,如果有相同字符,还要判断相同字符是否在当前考虑的子串范围内
例如,
2.哈希表的find函数,找的是key,例如,
hashtable["cat"] = 3;
auto it = hashtable.find("cat");
it->second = 3;
3.哈希表的find函数,如果找到了多个对应的键,会返回最后添加的那个匹配键的容器。
例如。
#include <iostream>
#include <unordered_map>
#include <string.h>
using namespace std;
int main(){
unordered_map<string,int>hashtable;
hashtable["cat"] = 0;
//hashtable["cat"] = 3;
hashtable["dog"] = 1;
hashtable["cat"] = 2;
hashtable["cat"] = 3;
int i = 3;
auto it = hashtable.find("cat");
i = i - it->second;
cout<<it->second<<endl;
return 0;
}
对于上述代码,得到的打印结果为3。如果将注释行取消注释,并且将最后一行添加的哈希表注释。则会得到打印结果2。
第一次自己做出来的题。。。不容易啊
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int max = 0;
int temp = 0;
unordered_map<char,int>hashtable;
for(int i = 0; i < s.length(); ++i){
auto it = hashtable.find(s[i]);
if(it == hashtable.end() || (it->second) < (i - temp)) //说明没有相同字符,或者相同字符不在当前子字符串范围中
{
temp ++;
if(temp > max)
max = temp;
}
else //有相同字符
{
temp = i - (it->second);
}
hashtable[s[i]] = i;
}
return max;
}
};