-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestSubstringWithoutRepeatingCharacters.php
More file actions
55 lines (48 loc) · 1.38 KB
/
Copy pathLongestSubstringWithoutRepeatingCharacters.php
File metadata and controls
55 lines (48 loc) · 1.38 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php
namespace App;
/**
* Longest Substring Without Repeating Characters
*
* 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.
*
* https://leetcode.com/problems/longest-substring-without-repeating-characters
*/
class LongestSubstringWithoutRepeatingCharacters
{
/**
* @param string $str
* @return int
*/
public function lengthOfLongestSubstring(string $str): int
{
$chars = [];
$left = 0;
$right = 0;
$result = 0;
$length = strlen($str);
while ($right < $length) {
$rightChar = $str[$right];
if (isset($chars[$rightChar])) {
$chars[$rightChar]++;
} else {
$chars[$rightChar] = 1;
}
while ($chars[$rightChar] > 1) {
$leftChar = $str[$left];
if (isset($chars[$leftChar])) {
$chars[$leftChar]--;
} else {
$chars[$leftChar] = 1;
}
$left++;
}
$result = max($result, $right - $left + 1);
$right++;
}
return $result;
}
}