Skip to content

Commit 97c3ef8

Browse files
committed
Valid Palindrome II
1 parent 257521b commit 97c3ef8

File tree

3 files changed

+75
-0
lines changed

3 files changed

+75
-0
lines changed

String/ValidPalindromeII.php

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<?php
2+
3+
namespace Hakam\LeetCodePhp\String;
4+
5+
class ValidPalindromeII
6+
{
7+
/**
8+
* @param String $s
9+
* @return Boolean
10+
*/
11+
12+
public function validPalindrome($s): bool
13+
{
14+
$right = strlen($s) - 1;
15+
$left = 0;
16+
while ($left < $right) {
17+
if ($s[$left] !== $s[$right]) {
18+
return $this->isPalindrome($s, $left + 1, $right) || $this->isPalindrome($s, $left, $right - 1);
19+
}
20+
$left++;
21+
$right--;
22+
}
23+
return true;
24+
}
25+
26+
private function isPalindrome($s, $i, $j): bool
27+
{
28+
while ($i < $j) {
29+
if ($s[$i++] !== $s[$j--]) {
30+
return false;
31+
}
32+
}
33+
return true;
34+
}
35+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
{
2+
"testCase1": {
3+
"expectedResult": false ,
4+
"input": "abcbaebg"
5+
},
6+
"testCase2": {
7+
"expectedResult": true ,
8+
"input": "abca"
9+
},
10+
"testCase3": {
11+
"expectedResult": true ,
12+
"input": " "
13+
},
14+
"testCase4": {
15+
"expectedResult": false ,
16+
"input": "abc"
17+
},
18+
"testCase5": {
19+
"expectedResult": true ,
20+
"input": "aba"
21+
}
22+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<?php
2+
3+
namespace Hakam\LeetCodePhp\Tests\String;
4+
5+
use Hakam\LeetCodePhp\String\ValidPalindromeII;
6+
use Hakam\LeetCodePhp\Tests\Helper\MainTest;
7+
8+
class ValidPalindromeIITest extends MainTest
9+
{
10+
/**
11+
* @dataProvider provideData
12+
*/
13+
public function testWithDataList($expectedResult, $inputData): void
14+
{
15+
$validatePalindrome = new ValidPalindromeII();
16+
self::assertEquals($expectedResult,$validatePalindrome->validPalindrome($inputData));
17+
}
18+
}

0 commit comments

Comments
 (0)