Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequence and not a substring.
方法一:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if(s.empty())
return 0;
int maxlen=0,start=-1;
unordered_map<char,int> dict;//存储字符及其下标
for(int i=0;i<s.size();i++)
{
auto it=dict.find(s[i]);
if(it!=dict.end())
start=max(start,it->second);//发现重复,更新子串start位置,start取较大值,因为可能发现在start之前出现过的字符
dict[s[i]]=i;//未重复,加入子串中
maxlen=max(maxlen,i-start);
}
return maxlen;
}
};
方法二:
不用hashmap,因为所有的字符ASCII码加起来也就最多256个,可以直接用数组来代替hashmap,效率更高。
注:ASCII码占用一个字节,可以有0~255共256个取值。前128个为常用的字符如运算符,字母 ,数字等 键盘上可以显示的后 128个为 特殊字符是键盘上找不到的字符。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if(s.empty())
return 0;
int maxlen=0,start=-1;
vector<int> dict(256,-1);//存储字符及其下标
for(int i=0;i<s.size();i++)
{
//auto it=dict.find(s[i]);
if(dict[s[i]]>start)
start=dict[s[i]];//发现重复,更新子串start位置,start取较大值,因为可能发现在start之前出现过的字符
dict[s[i]]=i;//未重复,使数组中s[i]位的值赋为对应下标
maxlen=max(maxlen,i-start);
}
return maxlen;
}
};