3.longest-substring-without-repeating-characters

Description:

Given a string s, find the length of the longest substring without repeating characters.

Constraints:

  • 0 <= s.length <= $5*10^4$
  • s consists of English letters, digits, symbols and spaces

Sliding Window










Appropriate Answer (Sliding Window):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php

namespace LeetCode\LongestSubstringWithoutRepeatintCharacters;

class Solution
{
/**
* @param string $string
* @return int
*/
public function lengthOfLongestSubstring($string)
{
$length = strlen($string);
if ($length == 0 || $length == 1) {
return $length;
}

$answer = 0;
$windowLeft = 0;
$windowRight = 0;
$usedCharacters = [];

while ($windowRight < $length) {
$character = $string[$windowRight];

while (
isset($usedCharacters[$character]) &&
$usedCharacters[$character] >= $windowLeft
) {
$windowLeft = $usedCharacters[$character] + 1;
}

$usedCharacters[$character] = $windowRight;
$windowRight++;

$answer = max($answer, $windowRight - $windowLeft);
}

return $answer;
}
}
  • Time Complexity: $O(n)$

ʕ •ᴥ•ʔ:一開始有嘗試暴力解,但最後一個test case跑不過。

[2026-03-13] 更新
昨天解題遇到類似的概念 (sliding windows)
給 AI 寫 test case 沒過。

回來翻這篇文章,發現題目是一樣的,
把題目轉成 c# 寫法後,居然還是沒過!

驚覺原本的寫法有 bug (但 leetcode 988/988 cased passed)
最後修正成上面這個樣子。

Share