题目描述
在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。
示例:
s = “abaccdeff”
返回 “b”
s = “”
返回 " "
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Java
class Solution {
public char firstUniqChar(String s) {
if(s.equals("")) return ' ';
Map<Character,Integer> map=new HashMap<>();
for(int i=0;i<s.length();i++){
char c=s.charAt(i);
if (map.containsKey(c))
map.put(c,map.get(c)+1);
else
map.put(c,1);
}
for(int i=0;i<s.length();i++){
char c=s.charAt(i);
if(map.get(c)==1){
return c;
}
}
return ' ';
}
}
优化
class Solution {
public char firstUniqChar(String s) {
if(s.equals("")) return ' ';
int [] hash=new int[26];
for(int i=0;i<s.length();i++) {
hash[s.charAt(i)-'a']++;
}
for(int i=0;i<s.length();i++){
if(hash[s.charAt(i)-'a']==1)
return s.charAt(i);
}
return ' ';
}
}
Java优化:查找字符串中首个仅出现一次的字符
本文介绍了如何使用Java优化解决LeetCode上的问题,通过哈希表快速找到字符串`s`中第一个只出现一次的字符,若无则返回空格。展示了两种代码实现方式对比。
507

被折叠的 条评论
为什么被折叠?



