开发者

How can I find the first non-repeating character in a string? [closed]

开发者 https://www.devze.com 2022-12-25 07:46 出处:网络
It's difficult to tell what is being asked h开发者_StackOverflow中文版ere. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its cu
It's difficult to tell what is being asked h开发者_StackOverflow中文版ere. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 10 years ago.

I need to write a function that returns the first non-repeating character in a string (case-insensitively). For example, for the string "Thanks for visiting" it should return "h".


You could make a pass over the characters in the string and store counts for each character (in a case-insensitive manner) in a hash. Then make another pass and return the first character with the count of 1:

sub get_char {
    my ($string) = @_;
    my @chars = split //, $string;
    my %chars;
    ++$chars{ lc() } for @chars;
    $chars{ lc() } == 1 && return $_ for @chars;
}

Apparently, this approach takes O(n) time and O(n) extra space.


sub { 
    # This assumes non-repeating means consecutive-repeating.
    # non-consecutive-repeating is too boring to answer
    my $string_copy = $_[0];
    $string_copy =~ s/(.)(\1)+//g; 
    return substr($string_copy ,0, 1)
}  


Using substr() and index():

sub get_it {
    my $string = shift;
    for my $i ( 0 .. length($string) - 1 ) {
        my $char = substr $string, $i, 1;
        return $char if index( $string, $char, $i + 1 ) >= 0;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号