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
42
<?php

namespace LeetCode\LongestSubstringWithoutRepeatintCharacters;

class Solution
{

/**
* @param string $string
* @return int
*/
public function lengthOfLongestSubstring($string)
{
$answer = 0;

$length = strlen($string);
if ($length == 0) {
return $answer;
}

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

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

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

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

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

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

Share