First Unique Character in a String

Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. Examples:

s = "leetcode"
return 0.
s = "loveleetcode",
return 2.

Note: You may assume the string contain only lowercase letters.

  1. 用一个新的list存index和同样字母出现的次数

    class Solution(object):
     def firstUniqChar(self, s):
         """
         :type s: str
         :rtype: int
         """
         indexes = [0] * len(s)
         for i in range(len(s)):
             indexes[s.index(s[i])] += 1
         for i in range(len(indexes)):
             if indexes[i] == 1:
                 return i
         return -1
    
  2. 有左右find确认出现的次数

    class Solution(object):
     def firstUniqChar(self, str1):
         """
         :type s: str
         :rtype: int
         """
         for x in str1:
             if str1.find(x)==str1.rfind(x):
                 return str1.find(x)
         return -1
    

Note: 只有string才有rfind/rindex。

results matching ""

    No results matching ""