Skip to content

Latest commit

 

History

History
52 lines (46 loc) · 1.06 KB

1694.重新格式化电话号码.md

File metadata and controls

52 lines (46 loc) · 1.06 KB

1694.重新格式化电话号码

/*
 * @lc app=leetcode.cn id=1694 lang=typescript
 *
 * [1694] 重新格式化电话号码
 */

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

解法 1: 模拟

function reformatNumber(number: string): string {
  const s = number
      .split('')
      .filter(ch => /[0-9]/.test(ch))
      .join(''),
    n = s.length
  const res: string[] = []
  for (let i = 0; i < n; i++) {
    if (n - i > 4) {
      res.push(s.slice(i, i + 3), '-')
      i += 2
    } else {
      if (n - i === 4) {
        res.push(s.slice(i, i + 2), '-', s.slice(i + 2, n))
      } else {
        res.push(s.slice(i, n))
      }
      break
    }
  }
  return res.join('')
}

Case

test.each([
  { input: { number: '1-23-45 6' }, output: '123-456' },
  { input: { number: '123 4-567' }, output: '123-45-67' },
  { input: { number: '123 4-5678' }, output: '123-456-78' },
])('input: number = $input.number', ({ input: { number }, output }) => {
  expect(reformatNumber(number)).toEqual(output)
})