Original text

Description

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

Example 1

Input: s = "abcabcbb"

Output: 3

Explanation: The answer is "abc", with the length of 3.

Example 2

Input: s = "bbbbb"

Output: 1

Explanation: The answer is "b", with the length of 1.

Example 3

Input: s = "pwwkew"

Output: 3

Explanation: The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.

Constraints

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

Solution (PHP 8.2)

function getLongestSubstringLength(string $input): int
{
    $inputLength = \strlen($input);

    $buffer = [];
    $longestSubstringLength = 0;
    for ($charIndex = 0; $charIndex < $inputLength; $charIndex++) {
        $char = \substr($input, $charIndex, length: 1);
        if (\in_array($char, $buffer)) {
            $buffer = [$char];

            continue;
        }

        $buffer[] = $char;

        $bufferLength = \count($buffer);
        if ($bufferLength > $longestSubstringLength) {
            $longestSubstringLength = $bufferLength;
        }
    }

    return $longestSubstringLength;
}
Debug
>> abcabcbb
 3 abc
 3 abc
 1 b
 1 b
<< 3
>> pwwkew
 2 pw
 3 wke
 1 w
<< 3
>> Lorem ipsum dolor sit amet
10 Lorem ipsu
 5 m dol
 6 or sit
 5  amet
<< 10

Tests

Input stringResultTimeMemory
abcabcbb365μs792B
bbbbb160μs576B
pwwkew326μs648B
Lorem ipsum dolor sit amet1055μs2088B
013μs56B
1161μs288B
11158μs360B
OS: Ubuntu WSL2 (5.15.146.1-microsoft-standard-WSL2)
CPU: AMD Ryzen 7 5800X
RAM: 16GB
PHP 8.2.17 (cli) (built: Mar 16 2024 08:41:44) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.2.17, Copyright (c) Zend Technologies
    with Zend OPcache v8.2.17, Copyright (c), by Zend Technologies
    with Xdebug v3.3.1, Copyright (c) 2002-2023, by Derick Rethans
memory_limit => -1
xdebug.mode => profile