1. 程式人生 > >leetcode-387. 字串中的第一個唯一字元

leetcode-387. 字串中的第一個唯一字元

一、問題描述

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

案例:

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

方法一:

1.程式碼和思路

因為字串是不可變的,這裡我們只能建立一個list來記錄列表中是否存在其重複

class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        n=len(s)
        s_list=[0]*n
        i=0
        while i<n:
            if i<n and s_list[i]==0:
                for j in range(i+1,n):
                    if s_list[j]==1:
                        continue
                    if s[j]==s[i]:
                        s_list[i]=s_list[j]=1
                if s_list[i]==0:
                    return i
            i += 1

        return -1

2.執行結果來看並不好

方法二:

1.程式碼和思路

先構建一個字典用來存放s中的元素的出現頻率,然後從頭開始編遍歷s,發現s中的元素中在字典中的value是1就返回該元素的位置

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

2.執行結果