1. 程式人生 > >leetcode (First Unique Character in a String)

leetcode (First Unique Character in a String)

Title:First Unique Character in a String   387

Difficulty:Easy

原題leetcode地址:https://leetcode.com/problems/first-unique-character-in-a-string/

 

1.    採用Map

時間複雜度:O(n),兩次一層for迴圈,最長遍歷整個字串。

空間複雜度:O(n),申請Map。

    /**
     * 將每個字元出現的次數存放到Map中,注意getOrDefault的使用
     * @param s
     * @return
     */
    public static int firstUniqChar(String s) {

        if (s.length() == 0) {
            return -1;
        }

        Map<Character, Integer> map = new HashMap<>();

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            map.put(c, map.getOrDefault(c, 0) + 1);
        }

        for (int i = 0; i < s.length(); i++) {
            if (map.get(s.charAt(i)) == 1) {
                return i;
            }
        }

        return -1;

    }