题目
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 “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) {
};
思路
- 这是一道求没有重复字符的最长子串的长度问题,需要进行一次遍历;
- 定义起始点
start = -1
,起始最大长度maxlen = 0
; - 遍历过程中若在前面找了当前的字符,则要修改起始点start并重新计算长度,并与原来的最大长度maxlen进行比较;
- 利用hash表来查找当前字符是比较快的,所以需要定义
unordered_map<char, int>
来存储已经遍历过的字符和它的下标;
代码
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> cmap;
int start{-1}, maxlen{0};
for (int i = 0; i != s.size(); ++i)
{
if (cmap.find(s[i]) != cmap.end())
{
start = max(start, cmap[s[i]]);
}
cmap[s[i]] = i;
maxlen = max(maxlen, i - start);
}
return maxlen;
}
};
运行时间56ms,不算快。
改进
- 上面的算法之所比较慢,不是因为思路不对,而是cmap.find()的执行速度不够快;
- 怎么办呢?考虑到string的字符集是有限个(256),所以当字符数超过256个时,必然能找到两个一样的字符,时间复杂度为O(1);
- 创建一个长度为256的
vector<int> vec(256,-1)
,它的下标序号就依次对应ASCII中的字符。一旦某个字符出现,就将它在原字符串中的序号存入,vec[s[i]] = i
。这样,每次查找必能在O(1)时间完成。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> vec(256, -1);
int start{-1}, maxlen{0};
for (int i = 0; i != s.size(); ++i)
{
if (vec[s[i]] != -1) //若访问过该字符
{
start = max(start, vec[s[i]]); //修改start为该字符对应字符串中的序号
}
vec[s[i]] = i; //把字符串中的序号存给数组的第s[i]位置
maxlen = max(maxlen, i - start);
}
return maxlen;
}
};
运行时间16ms,提高了不少