Skip to content

Commit d38dbe3

Browse files
committed
Longest Substring With At Most Two Distinct Characters
1 parent 4c761cf commit d38dbe3

File tree

3 files changed

+77
-0
lines changed

3 files changed

+77
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<?php
2+
3+
namespace Hakam\LeetCodePhp\String;
4+
5+
class LongestSubstringWithAtMostTwoDistinctCharacters
6+
{
7+
/**
8+
* @param String $s
9+
* @return Integer
10+
*/
11+
public function lengthOfLongestSubstringTwoDistinct( string $s): int
12+
{
13+
if (strlen($s) <= 2) {
14+
return strlen($s);
15+
}
16+
17+
$hashList = [];
18+
$left = 0;
19+
$right = 0;
20+
$maxLength = 0;
21+
22+
while ($right < strlen($s)) {
23+
$hashList [$s[$right]] = $right;
24+
$right++;
25+
if (count($hashList) === 3) {
26+
$del_index = min(array_values($hashList));
27+
unset($hashList[$s[$del_index]]);
28+
$left = $del_index + 1;
29+
}
30+
$maxLength = max($maxLength, $right - $left);
31+
}
32+
return $maxLength;
33+
}
34+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
{
2+
"testCase1": {
3+
"expectedResult": 3,
4+
"input": ["eceba"]
5+
},
6+
"testCase2": {
7+
"expectedResult": 4,
8+
"input": ["abaccc"]
9+
},
10+
"testCase3": {
11+
"expectedResult": 2,
12+
"input": ["aa"]
13+
},
14+
"testCase4": {
15+
"expectedResult": 5,
16+
"input": ["ccaabbb"]
17+
},
18+
"testCase5": {
19+
"expectedResult": 3,
20+
"input": ["abee"]
21+
}
22+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<?php
2+
3+
namespace Hakam\LeetCodePhp\Tests\String;
4+
5+
use Hakam\LeetCodePhp\String\LongestSubstringWithAtMostTwoDistinctCharacters;
6+
use Hakam\LeetCodePhp\Tests\Helper\MainTest;
7+
8+
/**
9+
* @covers \Hakam\LeetCodePhp\String\LongestSubstringWithAtMostTwoDistinctCharacters
10+
*/
11+
class LongestSubstringWithAtMostTwoDistinctCharactersTest extends MainTest
12+
{
13+
/**
14+
* @dataProvider provideData
15+
*/
16+
public function testWithDataList($expectedResult, $inputData): void
17+
{
18+
$findLongestSubString = new LongestSubstringWithAtMostTwoDistinctCharacters();
19+
self::assertEquals($expectedResult,$findLongestSubString->lengthOfLongestSubstringTwoDistinct($inputData[0]));
20+
}
21+
}

0 commit comments

Comments
 (0)