LeetCode题目--字符串中的第一个唯一字符(python实现)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_28266311/article/details/82995642

题目

给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -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

猜你喜欢

转载自blog.csdn.net/qq_28266311/article/details/82995642