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

坚强是说给别人听的谎言 提交于 2019-12-13 10:11:20

问题


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".


回答1:


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.




回答2:


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)
}  



回答3:


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;
    }
}


来源:https://stackoverflow.com/questions/2548606/how-can-i-find-the-first-non-repeating-character-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!