标签:put key 字符 temp unicode item line des 返回
Find the first unique character in a given string. You can assume that there is at least one unique character in the string.
For "abaccdeff"
, return ‘b‘
.
解题:返回仅出现一次,并且排在最前面的那个元素,而不是返回第一个不同的元素,一开始理解错了。如果仅仅对于ASCII中的256个字符,可以用数组来保存每个元素出现的次数。而对于Unicode中的元素,最好用HashMap来做。代码如下:
1 public class Solution {
2 /**
3 * @param str: str: the given string
4 * @return: char: the first unique character in a given string
5 */
6 public char firstUniqChar(String str) {
7 // Write your code here
8 HashMap<Character, Integer>map = new HashMap<Character, Integer>();
9 for(int i = 0; i < str.length(); i++){
10 char temp = str.charAt(i);
11 if(map.containsKey(temp)){
12 map.put(temp, map.get(temp) + 1);
13 }else{
14 map.put(temp, 1);
15 }
16 }
17 for(int i = 0; i < str.length(); i++)
18 if(map.get(str.charAt(i)) == 1)
19 return str.charAt(i);
20
21 return str.charAt(0);
22
23 }
24 }
209. First Unique Character in a String
标签:put key 字符 temp unicode item line des 返回
原文地址:https://www.cnblogs.com/phdeblog/p/9216524.html