LeetCode 387 字符串中的第一个唯一字符 (Python)

LeetCode第387题:

给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

案例:

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

思路如下:

  • 创建一个新的数组a,数组index代表26个字母
  • 遍历一遍字符串,统计每个字母出现的频率。例如当字符串第一个字母为a时,即数组下标为零的项存放的数值从零变为一(小写字母a的Asic_II码为97)
  • 遍历数组,将出现次数为一的字符加入list b中,若list为空则返回-1
  • 遍历上一步得到的list b和字符串,找到第一个不重复的字符并返回

代码如下:

from numpy import *
class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        a=zeros(26)
        b=[]
        for i in range(0,len(s)):
            index=ord(s[i])-97
            a[index]=a[index]+1
        for i in range(0,len(a)):
            if(a[i]==1):
                b.append(chr(i+97))
        if(len(b)==0):
            return -1
        result=len(s)-1
        for i in range(0,len(b)):
            for j in range(0,len(s)):
                if b[i]==s[j]:
                    if j<result:
                        result=j
        return result

猜你喜欢

转载自blog.csdn.net/Tianchi_M/article/details/82595755