美文网首页
Longest Substring Without Repeat

Longest Substring Without Repeat

作者: 我叫胆小我喜欢小心 | 来源:发表于2017-08-05 14:10 被阅读13次

题目来源
给一个字符串,判断里面的最长没有重复字符的子串。我是用哈希表来记录每个字符的最后出现的位置,以及记录一下当前字符串的开始位置,代码如下:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int n = s.size();
        unordered_map<char, int> map;
        int start = 0, res = 0;
        for (int i=0; i<n; i++) {
            if (map.count(s[i]) != 0 && map[s[i]] >= start)
                start = map[s[i]] + 1;
            map[s[i]] = i;
            res = max(res, i - start + 1);
        }
        return res;
    }
};

代码挺简洁的,不过不够快。不过也还行吧,至少不是数量级的差别。所以就这样吧。

相关文章

网友评论

      本文标题:Longest Substring Without Repeat

      本文链接:https://www.haomeiwen.com/subject/bynilxtx.html