原題鏈接: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
Python
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return -1
res = 0
letters = [0 for i in range(0, 26)]
for letter in s:
letters[ord(letter)-97] = letters[ord(letter)-97] + 1
for i in s:
if letters[ord(i)-97] == 1:
return s.index(i)
return -1
Tips:一定要細心,注意”cc”,”“這樣的字符串。邊界處理要做好!