diff --git a/README.md b/README.md index cb67cb1..120553f 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重 - LeetCode 面试题58 - II. 左旋转字符串 +- [最后一个单词的长度](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) diff --git a/src/string/length-of-last-word.js b/src/string/length-of-last-word.js new file mode 100644 index 0000000..80c68d2 --- /dev/null +++ b/src/string/length-of-last-word.js @@ -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 +} diff --git a/test/string/length-of-last-word.test.js b/test/string/length-of-last-word.test.js new file mode 100644 index 0000000..d368540 --- /dev/null +++ b/test/string/length-of-last-word.test.js @@ -0,0 +1,5 @@ +import { lengthOfLastWord } from '../../src/string/length-of-last-word' + +test('最后一个单词的长度', () => { + expect(lengthOfLastWord('b a ')).toBe(1) +})