LeetCode題目--字串中的第一個唯一字元(python實現)
阿新 • • 發佈:2018-11-11
題目
給定一個字串,找到它的第一個不重複的字元,並返回它的索引。如果不存在,則返回 -1。
案例:
s = "leetcode" 返回 0. s = "loveleetcode", 返回 2.
注意事項:您可以假定該字串只包含小寫字母。
python程式碼實現:
方法一:
class Solution: def firstUniqChar(self, s): """ :type s: str :rtype: int """ dic = collections.Counter(s) l=len(s) for i in range(0,l): if dic[s[i]] == 1: # 如果字典中value為1 return i return -1
方法二:
class Solution: def firstUniqChar(self, s): """ :type s: str :rtype: int """ l=len(s) num=[0]*l i=0 while i<l: n=s[i] if i<l and num[i]==0: for j in range(i+1,l): if s[j] == n : num[i]=num[j]=1 continue if num[i]==0: return i i+=1 return -1