Skip to content

Latest commit

 

History

History
48 lines (42 loc) · 1.01 KB

1003.检查替换后的词是否有效.md

File metadata and controls

48 lines (42 loc) · 1.01 KB

1003.检查替换后的词是否有效

/*
 * @lc app=leetcode.cn id=1003 lang=typescript
 *
 * [1003] 检查替换后的词是否有效
 */

// @lc code=start
function isValid(s: string): boolean {}
// @lc code=end

解法 1: 栈

function isValid(s: string): boolean {
  if (s[0] !== 'a' || s[s.length - 1] !== 'c') return false
  const stack: string[][] = []
  for (let ch of s) {
    if (ch === 'a') {
      stack.push([ch])
    } else {
      const last = stack[stack.length - 1]
      if (!last) return false
      if (ch === 'b') {
        if (last[last.length - 1] !== 'a') return false
        last.push(ch)
      } else if (last[last.length - 1] !== 'b') return false
      else stack.pop()
    }
  }
  return stack.length === 0
}

Case

test.each([
  { input: { s: 'aabcbc' }, output: true },
  { input: { s: 'abcabcababcc' }, output: true },
  { input: { s: 'abccba' }, output: false },
])('input: s = $input.s', ({ input: { s }, output }) => {
  expect(isValid(s)).toEqual(output)
})