开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜