1. 程式人生 > >209. First Unique Character in a String

209. First Unique Character in a String

數組 The desc HERE style IV contains item tle

Description

Find the first unique character in a given string. You can assume that there is at least one unique character in the string.

Example

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