Skip to content

Latest commit

 

History

History
62 lines (56 loc) · 1.28 KB

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

File metadata and controls

62 lines (56 loc) · 1.28 KB

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

/*
 * @lc app=leetcode.cn id=1807 lang=typescript
 *
 * [1807] 替换字符串中的括号内容
 */

// @lc code=start
function evaluate(s: string, knowledge: [string, string][]): string {}
// @lc code=end

解法 1: 模拟

function evaluate(s: string, knowledge: [string, string][]): string {
  const map = new Map(knowledge),
    n = s.length
  let res = ''
  for (let i = 0; i < n; i++) {
    if (s[i] === '(') {
      let word = ''
      for (let j = i + 1; j < n; j++) {
        if (s[j] === ')') {
          if (map.has(word)) res += map.get(word)
          else res += '?'
          i = j
          break
        } else {
          word += s[j]
        }
      }
    } else {
      res += s[i]
    }
  }
  return res
}

Case

test.each([
  {
    input: {
      s: '(name)is(age)yearsold',
      knowledge: [
        ['name', 'bob'],
        ['age', 'two'],
      ],
    },
    output: 'bobistwoyearsold',
  },
  { input: { s: 'hi(name)', knowledge: [['a', 'b']] }, output: 'hi?' },
  { input: { s: '(a)(a)(a)aaa', knowledge: [['a', 'yes']] }, output: 'yesyesyesaaa' },
])('input: s = $input.s, knowledge = $input.knowledge', ({ input: { s, knowledge }, output }) => {
  expect(evaluate(s, knowledge)).toEqual(output)
})