Find the first un-repeated character in a string

后端 未结 30 1385
猫巷女王i
猫巷女王i 2020-11-27 18:29

What is the quickest way to find the first character which only appears once in a string?

30条回答
  •  清歌不尽
    2020-11-27 19:05

    Here's an implementation in Perl (version >=5.10) that doesn't care whether the repeated characters are consecutive or not:

    use strict;
    use warnings;
    
    foreach my $word(@ARGV)
    {
      my @distinct_chars;
      my %char_counts;
    
      my @chars=split(//,$word);
    
      foreach (@chars)
      {
        push @distinct_chars,$_ unless $_~~@distinct_chars;
        $char_counts{$_}++;
      }
    
      my $first_non_repeated="";
    
      foreach(@distinct_chars)
      {
        if($char_counts{$_}==1)
        {
          $first_non_repeated=$_;
          last;
        }
      }
    
      if(length($first_non_repeated))
      {
        print "For \"$word\", the first non-repeated character is '$first_non_repeated'.\n";
      }
      else
      {
        print "All characters in \"$word\" are repeated.\n";
      }
    }
    

    Storing this code in a script (which I named non_repeated.pl) and running it on a few inputs produces:

    jmaney> perl non_repeated.pl aabccd "a huge string in which some characters repeat" abcabc
    For "aabccd", the first non-repeated character is 'b'.
    For "a huge string in which some characters repeat", the first non-repeated character is 'u'.
    All characters in "abcabc" are repeated.
    

提交回复
热议问题