【python程序员面试宝典|程序员算法宝典】

【python】判断一个字符串是否包含重复字符?

2019-07-25  本文已影响0人  阿牛02

题目:判断一个字符串是否包含重复字符。例如good则包含,abc则不包含。

分析:哈希法。

code:

(1)

strs = 'Good'

hashTable = dict()

listStrs = list(strs)

i = 0

while i < len(strs):

    if listStrs[i] in hashTable:

        print("有重复字符")

        break

    else:

        hashTable[listStrs[i]] = None

    i += 1

    if i >= len(strs):

        print("没用重复字符")

        break

程序运行结果:

有重复字符

(2)

def longest_repetition(chars):

    if len(chars) is None or len(chars) <= 1:

        return (chars, len(chars))

    result = [1] * len(chars)

    for left in range(len(chars) - 1):

        for right in range(left + 1, len(chars)):

            if chars[left] == chars[right]:

                print("a")

                result[left] += 1

            else:

                print("aa")

                break

    #return result

    return (chars[result.index(max(result))], max(result))

if __name__ == "__main__":

    txt = 'banaaana'

    print(longest_repetition(txt))

上一篇 下一篇

猜你喜欢

热点阅读