LeetCode-Solutions-in-Cpp17

Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.


Project maintained by downdemo Hosted on GitHub Pages — Theme by mattgraham
abcabcbb
01234567

l = 0, r = 0 a
l = 0, r = 1 ab => a  b 比较,无重复,不更新左边界
l = 0, r = 2 abc => ab  c 比较,无重复,不更新左边界
l = 0, r = 3 abca => abc  a 比较,a重复,更新左边界
l = 1, r = 3 bca
l = 1, r = 4 bcab => bca  b 比较,b 重复,更新左边界
l = 2, r = 4 cab
l = 2, r = 5 cabc => cab  c 比较,c 重复,更新左边界
l = 3, r = 5 abc
l = 3, r = 6 abcb => abc  b 比较,b 重复,更新左边界
l = 5, r = 6 cb
l = 5, r = 7 cbb => cb  b 比较,b 重复,更新左边界
l = 7, r = 7 b
l = 7, r = 8 r 越界,结束移动

上述过程中窗口无重复元素时,最大宽度为 3,结果即为 3
class Solution {
 public:
  int lengthOfLongestSubstring(string s) {
    int res = 0;
    int l = 0;
    for (int r = 0; r < size(s); ++r) {
      for (int i = l; i < r; ++i) {
        if (s[i] == s[r]) {
          l = i + 1;
          break;  // 后续不会再有重复值,可以提前结束此轮比较
        }
      }
      res = max(res, r - l + 1);
    }
    return res;
  }
};