add: 最后一个单词的长度

This commit is contained in:
yi-ge 2020-05-10 18:05:18 +08:00
parent 8a69d1cfb0
commit 6036e99c52
3 changed files with 20 additions and 0 deletions

View File

@ -71,6 +71,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
- LeetCode 面试题58 - II. 左旋转字符串 <https://leetcode-cn.com/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof/>
- [最后一个单词的长度](src/string/length-of-last-word.js)
- LeetCode 58. 最后一个单词的长度 https://leetcode-cn.com/problems/length-of-last-word/
- LintCode 422. 最后一个单词的长度 https://www.lintcode.com/problem/length-of-last-word/description
## 数组
- [电话号码的字母组合](src/array/letter-combinations-of-a-phone-number.js)

View File

@ -0,0 +1,10 @@
/**
* @param {string} s
* @return {number}
*/
export const lengthOfLastWord = function (s) {
s = s.trim()
const tmp = s.lastIndexOf(' ')
const lastWord = s.substring(tmp === -1 ? 0 : tmp + 1, s.length)
return lastWord.length
}

View File

@ -0,0 +1,5 @@
import { lengthOfLastWord } from '../../src/string/length-of-last-word'
test('最后一个单词的长度', () => {
expect(lengthOfLastWord('b a ')).toBe(1)
})