[leetcode]Add Bold Tag in String

python3

小心结尾。另外,zzz为s,zz为substr时,整个字符串都满足,所以要一个一个移动。

答案里用了startswith,更直观

class Solution:
    def addBoldTag(self, s: str, dict: List[str]) -> str:
        mark = [0] * len(s)
        for substr in dict:
            start = 0
            while start + len(substr) <= len(s):
                if s[start:].startswith(substr):
                    for i in range(len(substr)):
                        mark[start + i] = 1
                start += 1
        result = ''
        status = 0
        for i in range(len(mark)):
            if status == 0 and mark[i] == 0:
                result += s[i]
            elif status == 0 and mark[i] == 1:
                result += '<b>'
                result += s[i]
                status = 1
            elif status == 1 and mark[i] == 0:
                result += '</b>'
                result += s[i]
                status = 0
            elif status == 1 and mark[i] == 1:
                result += s[i]
            else:
                print ('Error')
            
        if status == 1:
            result += '</b>'
            status = 0
        return result

  

posted @ 2020-01-31 16:13  阿牧遥  阅读(142)  评论(0编辑  收藏  举报