LeetCode題解(0387):查找字符串中的第一個唯一字符的索引(Python)

題目:原題鏈接(簡單)

解法 時間複雜度 空間複雜度 執行用時
Ans 1 (Python) O(n) O(n) 204ms (27.88%)
Ans 2 (Python) O(n) O(n) 172ms (38.60%)
Ans 3 (Python) 100ms (85.37%)

LeetCode的Python執行用時隨緣,只要時間複雜度沒有明顯差異,執行用時一般都在同一個量級,僅作參考意義。

解法一(哈希表實現):

def firstUniqChar(self, s: str) -> int:
    hashmap = {}
    repeat = []
    for i in range(len(s)):
        c = s[i]
        if c not in repeat:
            if c not in hashmap:
                hashmap[c] = i
            else:
                del hashmap[c]
                repeat.append(c)
    if len(hashmap.values()) > 0:
        return min(hashmap.values())
    else:
        return -1

解法二(先找出目標字符,再獲取目標字符的索引):

def firstUniqChar(self, s: str) -> int:
    once = []
    repeat = []
    for c in s:
        if c not in repeat:
            if c not in once:
                once.append(c)
            else:
                once.remove(c)
                repeat.append(c)
    if len(once) > 0:
        return s.index(once[0])
    else:
        return -1

解法三(Pythonic):

def firstUniqChar(self, s: str) -> int:
    count = collections.Counter(s)
    for idx, ch in enumerate(s):
        if count[ch] == 1:
            return idx
    else:
        return -1
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章