美文网首页【python剑指offer】
【python】剑指offer,第一个只出现一次的字符?

【python】剑指offer,第一个只出现一次的字符?

作者: 阿牛02 | 来源:发表于2019-07-29 08:04 被阅读0次

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

分析:哈希表法。

code:

def FirstNotRepeatingChar(s):

    listS = list(s)

    hashTable = dict()

    i = 0

    while i < len(listS):

        if listS[i] not in hashTable:

            hashTable[listS[i]] = 1

        else:

            hashTable[listS[i]] = 0

        i += 1

    for k, v in hashTable.items():

        if v == 1:

            return k

    return -1

if __name__ == "__main__":

    s = "aabbcddffffj"

    print(FirstNotRepeatingChar(s))

程序运行结果:

c

相关文章

网友评论

    本文标题:【python】剑指offer,第一个只出现一次的字符?

    本文链接:https://www.haomeiwen.com/subject/leecrctx.html