387. 字符串的第一個唯一字符

一.題目

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

案例:

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

 

注意事項:您可以假定該字符串只包含小寫字母。

二.思路及代碼

暴力枚舉;(時間會炸)

class Solution:
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """        
        i = 0
        j = 0
        while i < len(s):
            while j < len(s):
                if s[i] != s[j] or i == j:
                    j += 1  
                else:
                    
                    break
            if j == len(s):
                return i
            else:
                j = 0
                i += 1
        return -1

hash table:以單個字母的string爲key,出現次數爲value構建一個字典(hash table),然後再從頭開始遍歷給定的string,根據構建好的hash table判斷,如果string裏的這個項在hash table裏的值爲1,那麼返回它的index,如果全部循環結束程序還沒終止,那就證明沒有合適的項,return -1。 

class Solution:
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """        
        hash_table = {}
        for i in s:
            if i not in hash_table:
                hash_table[i] = 1
            else:
                hash_table[i] += 1
        for j in range(len(s)):
            if hash_table[s[j]] == 1:
                return j
        return -1

利用字符串方法的str.find()和str.rfind()來判斷是否有重複字符。

class Solution:
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        s_set = set(s)
        indx_list=[]
        for i in s_set:
            first_indx = s.find(i)
            last_indx = s.rfind(i)
            if first_indx == last_indx:
                indx_list.append(first_indx)
        if indx_list == []:
            return -1
        else:
            return min(indx_list)

利用數組:因爲這個字符串裏的元素只能從26個字母裏選,所以,我們可以將26個字母的小寫形式構成一個字符串,然後循環這個字符串,計算每個字母在給定的s裏出現的次數,並將出現次數爲1的字母的index存起來,最後返回最小的index。

min(iterable) return value

class Solution:
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """

        # c = [i for i in range(len(s)) if s.count(s[i]) == 1]
        # if c != []:
        #     return min(c)
        # else:
        #     return -1
        
        temp = 'abcdefghijklmnopqrstuvwxyz'
        c = [s.index(i) for i in temp if s.count(i) == 1]
        return min(c or [-1])

註釋裏的方法和show出來的方法思路是一樣的,那爲什麼用26個小寫字母的循環,而不用註釋裏循環s的辦法呢?

這個要考慮時間和空間複雜度的問題,如果s很小那麼上面的方法ok,而如果s特別大會超時報錯。而第二種方法固定循環26次,還是很小的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章