How to find the last repeated character in a string with PHP

2 Answers

0 votes
function get_last_character_repeated($s) { 
    $len = strlen($s);
    $ch_idx = -1;
           
    for ($i = 0; $i < $len; $i++) { 
       for ($j = $i + 1; $j < $len; $j++) { 
            if ($s[$i] == $s[$j]) { 
                $ch_idx = $i;
                break;
            } 
        } 
    } 

    return $ch_idx; 
}  

$s = "abcdxypcbadom"; 
        
$i = get_last_character_repeated($s); 
       
if ($i == -1) {
    echo "Not found"; 
}
else {
     echo $s[$i];
}



    
/*
run:

d
         
*/

 



answered Jan 25, 2020 by avibootz
edited 5 days ago by avibootz
0 votes
/**
 * Finds the last repeated character in a string.
 *
 * Examples:
 *   "abca"          -> "a"
 *   "abcbd"         -> "b"
 *   "abcde"         -> null
 *   "abcdxypcbop"   -> "p"
 *   "abcdxypcbadom" -> "d"
 *
 * Time Complexity: O(n)
 * Space Complexity: O(k)
 *
 * @param string $input Input string.
 * @return ?string The last repeated character, or null if none exists.
 */
function findLastRepeatedCharacter(string $input): ?string
{
    // Count occurrences of each character.
    $frequency = [];
    $length = strlen($input);

    for ($i = 0; $i < $length; $i++) {
        $ch = $input[$i];
        $frequency[$ch] = ($frequency[$ch] ?? 0) + 1;
    }

    // Traverse from right to left.
    for ($i = $length - 1; $i >= 0; $i--) {
        $ch = $input[$i];

        if ($frequency[$ch] > 1) {
            return $ch;
        }
    }

    // No repeated character found.
    return null;
}

// Test cases
echo findLastRepeatedCharacter("abca"), PHP_EOL;         
echo findLastRepeatedCharacter("abcbd"), PHP_EOL;         

$result = findLastRepeatedCharacter("abcde");
echo ($result ?? ' '), PHP_EOL;                           

echo findLastRepeatedCharacter("abcdxypcbop"), PHP_EOL;   
echo findLastRepeatedCharacter("abcdxypcbadom"), PHP_EOL; 



/*
run:

a
b
 
p
d

*/

 



answered 5 days ago by avibootz
...