How can I find the first non-repeating character in a string? [closed]
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;
}
}
精彩评论