1. 程式人生 > 實用技巧 >LeetCode387-字串中的第一個唯一字元

LeetCode387-字串中的第一個唯一字元

非商業,LeetCode連結附上:

https://leetcode-cn.com/problems/first-unique-character-in-a-string/

進入正題。

題目:

給定一個字串,找到它的第一個不重複的字元,並返回它的索引。如果不存在,則返回 -1。

示例:

s = "leetcode"

返回 0

s = "loveleetcode"

返回 2

提示:你可以假定該字串只包含小寫字母。

程式碼實現:

//方法一 使用LinkedHashMap
public int firstUniqChar(String s) {

        Map<Character, Integer> map = new LinkedHashMap<>();
        for(int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if(map.containsKey(ch)) {
                map.put(ch, -1); 
            } else {
                map.put(ch, i);
            }
        }

        for(Map.Entry<Character, Integer> entry : map.entrySet()) {
            if(entry.getValue() >= 0) {
                return entry.getValue();
            }
        }

        return -1;
}
//時間複雜度O(n),空間複雜度O(n)

//方法二 兩次for迴圈遍歷
public int firstUniqChar(String s) {

        int n = s.length();
        Map<Character, Integer> map = new HashMap<>();
        for(int i = 0; i < n; i++) {
            char ch = s.charAt(i);
            map.put(ch, map.getOrDefault(ch, 0) + 1);
        }

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

        return -1;
}
//時間複雜度O(n),空間複雜度O(n)

分析:

使用語言內建的類,如HashMap或LinkedHashMap,要熟悉這些類的性質;

方法二第一次for迴圈統計字元出現的次數,第二次for迴圈從現向後判斷是否累計出現一次,第一個找到的即為目標索引。

--End