1. 程式人生 > 實用技巧 >LeetCode 雜湊表 387. 字串中的第一個唯一字元(計數雜湊表,字串)

LeetCode 雜湊表 387. 字串中的第一個唯一字元(計數雜湊表,字串)

啊,是較簡單的一題呢。有一些操作再熟悉一下。

思路就是建立一個HashMap用於計數,然後再遍歷就行。時間空間複雜度都是ON

自己寫的程式碼如下:

class Solution {
    public int firstUniqChar(String s) {
        HashMap<Character,Integer> map=new HashMap<Character,Integer>();
        for(int i=0;i<s.length();i++)
        {
            if(map.containsKey((Character)s.charAt(i)))
            {
                map.put(s.charAt(i),map.get(s.charAt(i))
+1); } else { map.put(s.charAt(i),1); } } for(int i=0;i<s.length();i++) { if(map.get(s.charAt(i))==1) { return i; } } return -1; } }

官方給的答案如下:

class Solution {
    public int firstUniqChar(String s) {
        HashMap<Character, Integer> count = new HashMap<Character, Integer>();
        int n = s.length();
        // build hash map : character and how often it appears
        for (int i = 0; i < n; i++) {
            
char c = s.charAt(i); count.put(c, count.getOrDefault(c, 0) + 1); } // find the index for (int i = 0; i < n; i++) { if (count.get(s.charAt(i)) == 1) return i; } return -1; } }

關於HashMap中幾個點注意一下

map.getOrDefault(c,0)這個api很好用,查不到值的時候直接返回預設值,就不用再節外生枝搞個判斷了。

map.constainsKey()這個api注意一下。

關於字串幾個點注意一下:

str.charAt(i) 直接以char型別返回索引處的字母

或者可以str.substring(i,i+1)

HashMap中放的是封裝類:Character類