How to find the first non-repeating character from a string?

I spent half a day trying to figure this out, and finally I got a working solution. However, I feel that this can be done easier. I think this code is not readable.

Problem: Find the first non-repeating character from the string.

$ string = "abbcabz"

In this case, the function should output "c".

The reason I use concatenation instead $input[index_to_remove] = '' to remove a character from a given string is because if I do, it just leaves an empty cell so that my return value $ input [0] does not return the character I want to return.

For instance,

$str = "abc";
$str[0] = '';
echo $str;

This will output "bc"

But actually, if I test,

var_dump($str);

he will give me:

string(3) "bc"

Here is my intention:

Given: input

while first char exists in substring of input {
  get index_to_remove
  input = chars left of index_to_remove . chars right of index_to_remove

  if dupe of first char is not found from substring
     remove first char from input 
}
return first char of input

the code:

function find_first_non_repetitive2($input) {

    while(strpos(substr($input, 1), $input[0]) !== false) {

        $index_to_remove = strpos(substr($input,1), $input[0]) + 1;
        $input = substr($input, 0, $index_to_remove) . substr($input, $index_to_remove + 1);

        if(strpos(substr($input, 1), $input[0]) == false) {
            $input = substr($input, 1);     
        }
    }
    return $input[0];
}
+5
8
<?php
    // In an array mapped character to frequency, 
    // find the first character with frequency 1.
    echo array_search(1, array_count_values(str_split('abbcabz')));
+9

Python:

def first_non_repeating(s):
 for i, c in enumerate(s):
  if s.find(c, i+1) < 0:
   return c
 return None

PHP:

function find_first_non_repetitive($s)
{
 for($i = 0; i < strlen($s); i++) {
  if (strpos($s, $s[i], i+1) === FALSE)
   return $s[i];
 }
}
+2

:

Array N;

For each letter in string
  if letter not exists in array N
    Add letter to array and set its count to 1
  else
    go to its position in array and increment its count
End for

for each position in array N
  if value at potition == 1
    return the letter at position and exit for loop
  else
    //do nothing (for clarity)
end for

, , , . , 1

O (n ^ 2) . , .

+1

, PHP:

// Count number of occurrences for every character
$counts = count_chars($string);

// Keep only unique ones (yes, we use this ugly pre-PHP-5.3 syntax here, but I can live with that)
$counts = array_filter($counts, create_function('$n', 'return $n == 1;'));

// Convert to a list, then to a string containing every unique character
$chars = array_map('chr', array_keys($counts));
$chars = implode($chars);

// Get a string starting from the any of the characters found
// This "strpbrk" is probably the most cryptic part of this code
$substring = strlen($chars) ? strpbrk($string, $chars) : '';

// Get the first character from the new string
$char = strlen($substring) ? $substring[0] : '';

// PROFIT!
echo $char;
+1

1- algotithm like mergesort ( quicksort )
2-


  • repetetvives

: +
: O (n log n) + O (n) = O (n log n)

    $string = "abbcabz"

    $string = mergesort ($string)
    // $string = "aabbbcz" 

char, , match repetetive

+1

Scala, :

def firstUnique(chars:List[Char]):Option[Char] = chars match { 
  case Nil => None
  case head::tail => {
    val filtered = tail filter (_!=head)
    if (tail.length == filtered.length) Some(head) else firstUnique(filtered)
  }
}

scala > firstUnique ( "abbcabz".toList)
res5: [ Char] = (c)

Haskell:

firstUnique :: [Char] -> Maybe Char
firstUnique [] = Nothing
firstUnique (head:tail) = let filtered = (filter (/= head) tail) in
            if (tail == filtered) then (Just head) else (firstUnique filtered)

* > firstUnique "abbcabz"

'c'

, , :

firstUnique :: Eq a => [a] -> Maybe a

- .

+1
source
$str="abbcade";
$checked= array(); // we will store all checked characters in this array, so we do not have to check them again

for($i=0; $i<strlen($str); $i++)
{
    $c=0;
    if(in_array($str[$i],$checked)) continue;

    $checked[]=$str[$i];

    for($j=$i+1;$j<=strlen($str);$j++)
    {
        if($str[$i]==$str[$j]) 
        {
            $c=1;
            break;  
        }
    }
    if($c!=1) 
    {
        echo "First non repetive char is:".$str[$i]; 
        break;
    }
}
+1
source

This should replace your code ...

$ array = str_split ($ string);
$ array = array_count_values ​​($ array);
$ array = array_filter ($ array, create_function ('$ key, $ val', 'return ($ val == 1);'));
$ first_non_repeated_letter = key (array_shift ($ array));

Edit: too soon. Called "array_unique", thought that it actually reset the duplicate values. But the character order must be preserved in order to find the first character.

+1
source

All Articles