Skip to content

58. 最后一个单词的长度

58. 最后一个单词的长度

代码

javascript
// 58. 最后一个单词的长度:https://leetcode.cn/problems/length-of-last-word/description/
// 输入:"Hello World"
// 输出:5

export function lengthOfLastWord (s) {
  s = s.trim()
  let res = 0
  for (let i = s.length - 1; i >= 0; i--) {
    if (s[i] === ' ') {
      break
    }
    res++
  }
  return res
}
typescript
// 58. 最后一个单词的长度:https://leetcode.cn/problems/length-of-last-word/description/
// 输入:"Hello World"
// 输出:5

export function lengthOfLastWord (s: string): number {
  s = s.trim()
  let res = 0
  for (let i = s.length - 1; i >= 0; i--) {
    if (s[i] === ' ') {
      break
    }
    res++
  }
  return res
}

测试代码

ts
import { expect, test } from 'vitest'
import { lengthOfLastWord } from './typescript.ts'
import { lengthOfLastWord as lengthOfLastWordJs } from './javascript.js'

test(`lengthOfLastWord`, () => {
  expect(lengthOfLastWord('Hello World')).toBe(5)
  expect(lengthOfLastWord('   fly me   to   the moon  ')).toBe(4)
})

test(`lengthOfLastWordJs`, () => {
  expect(lengthOfLastWordJs('Hello World')).toBe(5)
  expect(lengthOfLastWordJs('   fly me   to   the moon  ')).toBe(4)
})