美文网首页【python公司校招题】
【python欢聚时代】字符串连连看?

【python欢聚时代】字符串连连看?

作者: 阿牛02 | 来源:发表于2019-08-10 20:22 被阅读0次

    题目:对于输入的字符串,从左到右扫描字符串,如果存在由三个以上(包括三个)连续相同字符组成的子串,就将这个子串从原串中去掉,并将原有字符串剩下的部分拼接到一起。重复上述过程,直到无法去掉任何子串

    输入描述:

    输入的字符串

    输出描述:

    最后剩下的子串

    示例1

    输入

    AAABCCDDDCB

    输出

    BB

    code:

    def removeDup(s):

        if s is None:

            print("参数不合法")

        if len(s) <= 2:

            return s

        flag = True

        while flag:

            flag = False

            i = 0

            for j in range(1, len(s)):

                while j < len(s) and s[j] == s[i]:

                    j += 1

                if j - i >= 3:

                    s = s[:i] + s[i + 3:]

                    flag = True

                    break

                else:

                    i = j

                    j = i + 1

        return s

    if __name__ == "__main__":

        s = 'AAABBBAAABBBAAAABBBAABBBAAAABBBBA'

        print(removeDup(s))

    程序运行结果:

    ABA

    相关文章

      网友评论

        本文标题:【python欢聚时代】字符串连连看?

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