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

3 Answers

0 votes
function get_first_repeated_character($s) {
    $len = strlen($s);

    for ($i = 0; $i < $len; $i++) {
        for ($j = 0; $j < $i; $j++) {
            if ($s[$i] == $s[$j]) {
                return $s[$i];
            }
        }
    }

    return "-";
}

$s = "abcdxypcbop";

$result = get_first_repeated_character($s);

if ($result != "-") {
    echo "First repeated character: $result\n";
} else {
    echo "No repeated characters\n";
}




/*
run:
   
First repeated character: c
   
*/

 



answered Sep 5, 2022 by avibootz
edited Dec 2, 2024 by avibootz
0 votes
/**
 * Finds the first repeated character in a string.
 *
 * Examples:
 *   "abca"         -> "a"
 *   "abcbd"        -> "b"
 *   "abcde"        -> null
 *   "abcdxypcbop"  -> "c"
 *
 * Time Complexity: O(n)
 * Space Complexity: O(n)
 *
 * @param string $input The input string.
 * @return ?string The first repeated character, or null if none exists.
 */
function findFirstRepeatedCharacter(string $input): ?string
{
    $seen = [];

    $length = strlen($input);

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

        // If we've seen this character before,
        // it is the first repeated character.
        if (isset($seen[$ch])) {
            return $ch;
        }

        $seen[$ch] = true;
    }

    // No repeated character found.
    return null;
}

// Test cases
var_dump(findFirstRepeatedCharacter("abca"));         
var_dump(findFirstRepeatedCharacter("abcbd"));        
var_dump(findFirstRepeatedCharacter("abcde"));        
var_dump(findFirstRepeatedCharacter("abcdxypcbop"));  
 
 
/*
run:
    
string(1) "a"
string(1) "b"
NULL
string(1) "c"
    
*/

 



answered 6 days ago by avibootz
0 votes
/**
 * Finds the first repeated character in a string.
 *
 * Examples:
 *   "abca"         -> "a"
 *   "abcbd"        -> "b"
 *   "abcde"        -> null
 *   "abcdxypcbop"  -> "c"
 *
 * Time Complexity: O(n)
 * Space Complexity: O(n)
 *
 * @param string $input The input string.
 * @return ?string The first repeated character, or null if none exists.
 */
function findFirstRepeatedCharacter(string $input): ?string
{
    $seen = [];

    $length = strlen($input);

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

        // If we've seen this character before,
        // it is the first repeated character.
        if (isset($seen[$ch])) {
            return $ch;
        }

        $seen[$ch] = true;
    }

    // No repeated character found.
    return null;
}

$testCases = [
    "abca",
    "abcbd",
    "abcde",
    "abcdxypcbop"
];

foreach ($testCases as $input) {
    $result = findFirstRepeatedCharacter($input);

    echo ($result ?? "No repeated character") . PHP_EOL;
}
 
 
/*
run:
    
a
b
No repeated character
c
    
*/

 



answered 6 days ago by avibootz
...