LeetCode 387. First Unique Character in a String (字符串中的第一个唯一字符)

题目标签:String, HashMap

  题目给了我们一个 string,让我们找出 第一个 唯一的 char。

  设立一个 hashmap,把 char 当作 key,char 的index 当作value。

  遍历string,如果这个 char 没有在 map 里,说明第一次出现,存入 char,index;

                     如果这个 char 已经在 map 里,说明不是第一次出现,而且我们不在乎这种情况,更新 char, -1。

  遍历hashmap,把最小的 index 的值找出来,返回即可。

 

 

Java Solution:

Runtime beats 41..82% 

完成日期:08/19/2018

关键词:HashMap

关键点:把index 存入map

 1 class Solution 
 2 {
 3     public int firstUniqChar(String s) 
 4     {
 5         HashMap<Character, Integer> map = new HashMap<>();
 6         char[] arr = s.toCharArray();
 7         
 8         for(int i=0; i<arr.length; i++)
 9         {
10             char c = arr[i];
11             Integer v = map.get(c);
12             
13             if(v != null) // if a char goes here, means that it is not a unique one
14                 map.put(c, -1);
15             else // unique char only goes here once
16                 map.put(c, i);
17         }
18         
19         
20         int minIndex = Integer.MAX_VALUE;
21         // find a min index char by iterating hashMap
22         for(Character key : map.keySet())
23         {
24             Integer v = map.get(key);
25             
26             if(v >= 0 ) 
27                 minIndex = Math.min(minIndex, v);
28 
29         }
30             
31         return minIndex == Integer.MAX_VALUE ? -1 : minIndex;
32     }
33 }

参考资料:https://leetcode.com/problems/first-unique-character-in-a-string/discuss/161004/Java-one-pass-O(1)-space-solution

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

posted @ 2018-08-20 05:25  Jimmy_Cheng  阅读(209)  评论(0编辑  收藏  举报