[Leetcode]58. Length of Last Word

58. Length of Last Word

題目連結
難易度:Easy

Given a string s consists of upper/lower-case alphabets and empty space characters ‘ ‘, return the length of last word in the string.

If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.

For example,

1
2
Given s = "Hello World",
return 5.

找出給定一字串包含大小寫及空白字元,回傳最長的單字

思路

這題來試試看不熟悉的正規表達式,先定義出regex = /\S/g\S其代表的意思是任何非空白鍵字元,若沒加g則只會匹配第一個找到的字元,
先用這個regex規則濾出沒有英文字的input, 使用match()來驗證,若返回null或input為空則return 0,接著使用trim()去除掉input的前後無效空白,
最後用split(' ')以空格拆解字串成陣列,回傳最後一個單字的長度即可。

解題

1
2
3
4
5
6
7
8
9
10
/**
* @param {string} s
* @return {number}
*/
var lengthOfLastWord = function(s) {
var regex = /\S/g;
if(s.match(regex) === null|| s=== '') return 0;
var result = s.trim().split(' ');
return result[result.length-1].length;
};