第一个只出现一次的字符

在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).(从0开始计数)

使用python内置函数:

class Solution:
    def FirstNotRepeatingChar(self, s):
        if not s:
            return -1
        try:
            s = s.strip()
            for i,c in enumerate(s):
                if s.count(c)==1:
                    return i
                    break
        except:
            return -1

使用collections.OrderedDict
【1】OrderedDict是有顺序的,而Dict是无序的。

from collections import OrderedDict
class Solution:
    def FirstNotRepeatingChar(self, s):
        hashTable = OrderedDict()
        for i in s:
            if i not in hashTable:
                hashTable[i] = 1
            else:
                hashTable[i] += 1
        for j in hashTable:
            if hashTable[j] == 1:
                return s.index(j)
        return -1

使用数组实现简单的hash表
【2】ord() 给定一个Unicode字符,返回ASCII码;A-Z的ASCII码为65-90,a-z的ASCII码值为97-122

class Solution:
    def FirstNotRepeatingChar(self, s):
        ls = [0]*123
        for i in s:
            ls[ord(i)] += 1
        for j in s:
            if ls[ord(j)] == 1:
                return s.index(j)
        return -1

如果某字符只出现一次,那么该字符的从前往后的索引和从后往前的索引是相等的
【3】index() 返回从前往后的第一个索引;rindex()返回从后往前的索引
还可使用find() 和 rfind(),不同之处在于 index() 查不到时抛出异常,而find() 返回-1

class Solution:
    def FirstNotRepeatingChar(self, s):
        for i in s:
            if s.index(i) == s.rindex(i):
                return s.index(i)
        return -1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值