刷题打卡第二天。。。
题目
在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。
示例
s = "abaccdeff"
返回 "b"s = ""
返回 " "
思路
- 统计每个字符出现的次数
- 循环统计次数的结果,第一个次数为1的字符便是结果了
代码编写
class Solution {
/**
* @param String $s
* @return String
*/
function firstUniqChar($s) {
if ($s == '') { return ' '; }
$s = str_split($s);
$counts = array_count_values($s);
foreach ($counts as $v => $count) {
if ($count === 1) {
return $v;
}
}
return ' ';
}
}
学习
题解的思路
- 遍历字符串,如果当前字符串已经存在过,将hashMap此键对应值设为false
- 循环hashMap,第一个值为true的键便是答案。
思路大致是一致的,省去了计算每个键对应次数的逻辑,会更快一些
python
class Solution:
def firstUniqChar(self, s: str) -> str:
dic = {}
for c in s:
dic[c] = not c in dic
for k, v in dic.items():
if v: return k
return ' '
总结
此题主要考察hashMap的使用,还需要在做题的时候,减少一些非必要的逻辑计算,节省时间