Created
December 6, 2019 18:32
-
-
Save adrianosferreira/b9b4ee146c84ac34b27a9bcb2e236d7c to your computer and use it in GitHub Desktop.
Palindrome in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function isPalindrome( $s ) { | |
$i = 0; | |
$j = strlen( $s ) - 1; | |
while ( $i < $j ) { | |
if ( $s[ $i ] !== $s[ $j ] ) { | |
return false; | |
} | |
$j --; | |
$i ++; | |
} | |
return true; | |
} | |
function countPalindromeSubStrings( $s ) { | |
$i = 0; | |
$palindromes = []; | |
$s = implode( '|', str_split( $s ) ); | |
while ( $i < strlen( $s ) ) { | |
if ( ! isset( $palindromes[ $s[ $i ] ] ) && $s[ $i ] !== '|' ) { | |
$palindromes[ $s[ $i ] ] = true; | |
} | |
$j = $i - 1; | |
$k = $i + 1; | |
$palindrome = ''; | |
while ( $k < strlen( $s ) ) { | |
if ( $j < 0 || $k > strlen( $s ) ) { | |
break; | |
} | |
if ( ! $palindrome && $s[ $i ] !== '|' ) { | |
$palindrome = $s[ $i ]; | |
} | |
if ( $s[ $j ] === $s[ $k ] && $s[ $j ] !== '|' && $s[ $k ] !== '|' ) { | |
$palindrome = $s[ $j ] . $palindrome . $s[ $k ]; | |
if ( ! isset( $palindromes[ $palindrome ] ) ) { | |
$palindromes[ $palindrome ] = true; | |
} | |
} | |
$j --; | |
$k ++; | |
} | |
$i ++; | |
} | |
return $palindromes; | |
} | |
//var_dump( countPalindromeSubStrings( 'abaaba' ) ); | |
isPalindrome( 'aa' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment