面试题48

请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。

示例 1:

输入: "abcabcbb"
输出: 3 
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。

示例 2:

输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。

示例 3:

输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
     请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。

提示:

  • s.length <= 40000

Solutions

  • See more solutions in problem 3

  • hash map

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int res = 0, last = -1;
        vector<int> prev(128, -1);
        for (int i = 0; i < s.size(); i++) {
            last = max(last, prev[s[i]]);
            res = max(res, i - last);
            prev[s[i]] = i;
        }

        return res;
    }
};
  1. two pointers with counter

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int i = 0, j = 0, res = 0;
        int counter[128] = {0};
        while (j < s.size()) {
            if (++counter[s[j++]] == 2)
                while (--counter[s[i++]] != 1);
            if (j - i > res)
                res = j - i;
        }
        res = max(res, j - i);

        return res;
    }
};

Last updated

Was this helpful?