hihocoder 1039 解题报告(python)

1039_字符消除

题目链接: http://hihocoder.com/problemset/problem/1039

很久没刷题了赶紧刷点水题以免各种面试被bs

题目大意:

中文题目直接看题就懂

思路:

一时间也没有什么很好的感觉速度很快的思路,只好老老实实按照题目意思一步步的进行,还好能够AC.首先要考虑插入一个字母,位置可以是字符串中的任意一个位置,我也没多想这里直接用字符串拼接来完成。对于消除操作,写了一个函数来做这件事情,要消除所有连续出现的相同字母,直接用re的替换函数来实现,直到findall()函数返回空表示已经消除完成。

python代码:

# coding= utf-8
import sys
import re

if __name__ == "__main__":
    def eliminate_string(s):
        pat = re.compile(r"A{2,}|B{2,}|C{2,}")
        while pat.findall(s):
            s = re.sub(pat, "", s)
        return s

    numLines = int(sys.stdin.readline())
    for i in range(1, numLines + 1):
        line = sys.stdin.readline()
        oldLen = len(line)
        minLen = oldLen
        for insertIndex in range(0, oldLen - 1):
            for c in ("A", "B", "C"):
                newLine = line[:insertIndex] + c + line[insertIndex:]  # 插入一个字母后的字符串
                lineLeft = eliminate_string(newLine)
                if len(lineLeft) < minLen:
                    minLen = len(lineLeft)
                    minLine = lineLeft
        print oldLen - minLen + 1  # 算的是插入一个字母之后的消除长度
原文地址:https://www.cnblogs.com/jolin123/p/4806801.html