Skip to content

Instantly share code, notes, and snippets.

@adrianosferreira
Created December 9, 2019 18:28
Show Gist options
  • Save adrianosferreira/e0f3d9abdd6f13ba14848553f20c9c84 to your computer and use it in GitHub Desktop.
Save adrianosferreira/e0f3d9abdd6f13ba14848553f20c9c84 to your computer and use it in GitHub Desktop.
Permutation in String with PHP.
<?php
class Solution {
/**
* @param String $s1
* @param String $s2
* @return Boolean
*/
function checkInclusion($s1, $s2) {
$map = [];
for( $i = 0; $i < strlen( $s1 ); $i ++ ) {
if ( ! isset( $map[ $s1[$i] ] ) ) {
$map[ $s1[$i] ] = 0;
}
$map[ $s1[$i] ] ++;
}
$i = 0;
$j = 0;
$temp = [];
while( $i < strlen($s2) ) {
if ( $j - $i === strlen($s1) ) {
return true
}
if ( ! isset( $map[$s2[$j]] ) ) {
$i = $j + 1;
$j = $i;
unset( $temp );
continue;
}
if ( ! isset($temp[ $s2[$j] ]) ) {
$temp[ $s2[$j] ] = 0;
}
$temp[ $s2[$j] ] ++;
if ( $temp[ $s2[$j] ] > $map[ $s2[$j] ] ) {
$i ++;
$j = $i;
unset( $temp );
} else {
$j ++;
}
}
return false;
}
}
$solution = new Solution();
$solution->checkInclusion( 'abc', 'eeeeeeeebca' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment