Skip to content

Instantly share code, notes, and snippets.

@adrianosferreira
Created December 17, 2019 17:18
Show Gist options
  • Save adrianosferreira/b2737bf230e3566977287e936dd784e5 to your computer and use it in GitHub Desktop.
Save adrianosferreira/b2737bf230e3566977287e936dd784e5 to your computer and use it in GitHub Desktop.
Find space between a word
<?php
function longestSpaceBetweenWord( $s, $word ) {
$wordMapBkp = wordMap( $word );
$wordMap = $wordMapBkp;
$i = 0;
$j = 0;
$programmerStrings = [];
$max = 0;
while( $j < strlen( $s ) ) {
if ( isset( $wordMap[ $s[ $j ] ] ) && $wordMap[ $s[ $j ] ] > 0 ) {
$wordMap[ $s[ $j ] ] --;
if ( $j - $i === strlen( $word ) - 1 ) {
$newWord = [ 'start' => $i, 'end' => $j ];
if ( $programmerStrings ) {
$last = array_pop( $programmerStrings );
$length = $newWord[ 'start' ] - $last[ 'end' ] - 1;
if ( $max < $length ) {
$max = $length;
}
}
$programmerStrings[] = $newWord;
}
$j ++;
} elseif ( $i === $j ) {
$i ++;
$j ++;
} else {
$i = $j;
$wordMap = $wordMapBkp;
}
}
echo $max;
}
function wordMap( $word ) {
$map = [];
for( $i = 0; $i < strlen( $word ); $i ++ ) {
if ( ! isset( $map[ $word[ $i ] ] ) ) {
$map[ $word[ $i ] ] = 0;
}
$map[ $word[ $i ] ] ++;
}
return $map;
}
longestSpaceBetweenWord( 'programmerabcprogrammer', 'programmer' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment