Created
November 14, 2019 19:13
-
-
Save adrianosferreira/f43a5c0fc6330ebcdcb3eecf99965e11 to your computer and use it in GitHub Desktop.
Distance between strings in PHP
This file contains hidden or 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 | |
/** | |
* Created by PhpStorm. | |
* User: adriano | |
* Date: 11/11/19 | |
* Time: 21:51 | |
*/ | |
function programmerStrings( $s ) { | |
$possibleLetters = getPossibleLetters(); | |
$stringArr = str_split( $s ); | |
$maxSpace = 0; | |
$currentLen = 0; | |
$wordLen = 2; | |
$end = null; | |
$start = null; | |
foreach ( $stringArr as $key => $letter ) { | |
if ( isset( $possibleLetters[ $letter ] ) ) { | |
if ( $possibleLetters[ $letter ] > 0 ) { | |
if ( $start === null ) { | |
$start = $key; | |
} | |
$currentLen ++; | |
$possibleLetters[ $letter ] --; | |
} else { | |
$start = $key; | |
} | |
} | |
if ( $currentLen === $wordLen ) { | |
if ( $start && $end ) { | |
$space = $start - $end - 1; | |
if ( ! $maxSpace || $space > $maxSpace ) { | |
$maxSpace = $space; | |
} | |
} | |
$end = $key; | |
$start = null; | |
$possibleLetters = getPossibleLetters(); | |
$currentLen = 0; | |
} | |
} | |
return $maxSpace; | |
} | |
function getPossibleLetters() { | |
return [ | |
'h' => 1, | |
'i' => 1, | |
]; | |
} | |
assert( 0 === programmerStrings( 'hihi' ) ); | |
assert( 0 === programmerStrings( 'hi' ) ); | |
assert( 2 === programmerStrings( 'hiiiihi' ) ); | |
assert( 5 === programmerStrings( 'hiqqqqqhi' ) ); | |
assert( 1 === programmerStrings( 'hiiih' ) ); | |
assert( 8 === programmerStrings( 'hiiiihiiiiiiiiih' ) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment