LeetCode.387.First Unique Character in a String

原题链接: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”,”“这样的字符串。边界处理要做好!

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