面試題50.第一個只出現一次的字符
題目描述
在字符串 s 中找出第一個只出現一次的字符。如果沒有,返回一個單空格。
示例:
s = “abaccdeff”
返回 “b”
s = “”
返回 " "
限制:
0 <= s 的長度 <= 50000
題解1
藉助雙列集合HashMap,將字符串轉換成字符數組後遍歷字符數組並加入集合中,加入的同時,判斷是否已經加入過,如果是,則將值置爲2,未加入過則置1;然後遍歷打印第一個值爲1字符;
class Solution {
public char firstUniqChar(String s) {
HashMap<Character,Integer> hm = new HashMap<>();
char[] ch = s.toCharArray();
for(char c : ch){
if(!hm.containsKey(c)){
hm.put(c,1);
}else{
hm.put(c,2);
}
}
for(char c:ch){
if(hm.get(c)==1){
return c;
}
}
return ' ';
}
}
題解2
藉助字典,將’a~z’存入字典,兩次遍歷,第一次將字符統計如字典數組,第二次遍歷從字典獲取次數,返回出現一次的字符,代碼如下:
class Solution {
public char firstUniqChar(String s) {
if(s.equals("")) return ' ';
int[] ziDian = new int[26];
for(int i = 0;i<s.length();i++){
ziDian[s.charAt(i) - 'a']++;
}
for(int i = 0;i<s.length();i++){
if(ziDian[s.charAt(i) - 'a']==1)
return s.charAt(i);
}
return ' ';
}
}
提交結果
方法一:
方法二: