From 6036e99c52df4f690c3265920f42b3b621463531 Mon Sep 17 00:00:00 2001 From: yige Date: Sun, 10 May 2020 18:05:18 +0800 Subject: [PATCH] =?UTF-8?q?add:=20=E6=9C=80=E5=90=8E=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E5=8D=95=E8=AF=8D=E7=9A=84=E9=95=BF=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 5 +++++ src/string/length-of-last-word.js | 10 ++++++++++ test/string/length-of-last-word.test.js | 5 +++++ 3 files changed, 20 insertions(+) create mode 100644 src/string/length-of-last-word.js create mode 100644 test/string/length-of-last-word.test.js 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) +})