版权声明
1. 剑指 Offer 50
1.1 复杂度分析
- 哈希表:无需复习
- 时间复杂度:
O(n);
- 空间复杂度:
O(n);
1.2 哈希表
- 解题思路:
- 第一次遍历字符串中的每个字符:以字符为键,出现次数为值,存入哈希表中;
- 第二次遍历字符串中的每个字符:查询该字符对应的出现次数,若出现次数为1,即为所求;
class Solution {
public char firstUniqChar(String s) {
HashMap<Character, Integer> st = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char temp = s.charAt(i);
if (st.containsKey(temp))
st.put(temp, st.get(temp) + 1);
else
st.put(temp, 1);
}
for (int i = 0; i < s.length(); i++)
if (st.get(s.charAt(i)) == 1)
return s.charAt(i);
return ' ';
}
}
2. Summary
References