387. 字符串中的第一個唯一字符.py-----leetcode刷題(python解題)

[TOC]

題目

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

案例:

        s = "leetcode"
      

返回 0.

        s = "loveleetcode",
      

返回 2.

注意事項:您可以假定該字符串只包含小寫字母。

來源:力扣(LeetCode) 鏈接:leetcode-cn.com/problem 著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

解答

leetcode解題

        import collections

class Solution1(object):  # 方法一
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        for a,i in enumerate(s):
            aa = s.replace(i,"",1)
            if i not in aa:
                return a


class Solution2(object):  # 方法二
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        index=0
        count = collections.Counter(s)
        for i in s:
            if count[i]==1:
                return index
            else:
                index+=1
        return -1
      

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