Skip to content

Latest commit

 

History

History
45 lines (39 loc) · 817 Bytes

1653.使字符串平衡的最少删除次数.md

File metadata and controls

45 lines (39 loc) · 817 Bytes

1653.使字符串平衡的最少删除次数

/*
 * @lc app=leetcode.cn id=1653 lang=typescript
 *
 * [1653] 使字符串平衡的最少删除次数
 */

// @lc code=start
function minimumDeletions(s: string): number {}
// @lc code=end

解法 1: 枚举

function minimumDeletions(s: string): number {
  const n = s.length
  let res = Infinity,
    a = 0,
    b = 0
  for (const ch of s) {
    if (ch === 'a') a++
  }
  res = Math.min(a, n - a)
  for (let i = 0; i < n; i++) {
    if (s[i] === 'a') a--
    else b++
    res = Math.min(res, b + a)
  }
  return res
}

Case

test.each([
  { input: { s: 'aababbab' }, output: 2 },
  { input: { s: 'bbaaaaabb' }, output: 2 },
])('input: s = $input.s', ({ input: { s }, output }) => {
  expect(minimumDeletions(s)).toEqual(output)
})