如何找到字符串中的第一个非重复字符? [英] How can I find the first non-repeating character in a string?
本文介绍了如何找到字符串中的第一个非重复字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要编写一个函数,该函数返回字符串中的第一个非重复字符(不区分大小写).例如,对于字符串"Thanks for visiting"
,它应返回"h"
.
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;
}
显然,这种方法需要花费O(n)
的时间和O(n)
的额外空间.
Apparently, this approach takes O(n)
time and O(n)
extra space.
这篇关于如何找到字符串中的第一个非重复字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文