LeetCode每日一题:Day12

发布于 2023-01-12  93 次阅读


1807. 替换字符串中的括号内容

难度

  • Easy
  • Medium
  • Hard

思路

简单模拟题。

代码

class Solution:
    def evaluate(self, s: str, knowledge: List[List[str]]) -> str:
        idx, n, ans, mapping, is_key, tmp = 0, len(s), "", {}, False, ""
        for key, value in knowledge:
            mapping[key] = value

        while idx < n:
            if s[idx] == '(':
                is_key = True
            elif s[idx] == ')':
                is_key = False
                if tmp not in mapping:
                    ans += '?'
                else:
                    ans += mapping[tmp]
                tmp = ""
            else:
                if is_key:
                    tmp += s[idx]
                else:
                    ans += s[idx]
            idx += 1

        return ans