Image From LeetCodeImage From LeetCode

今天我們要講解的是 [Length Of Last Word],這在 LeetCode 算是比較簡單的題目,讓我們一起開始吧!

進來之前請先注意,我的方式不一定完全正確,只是依照我自己的理念進行撰寫,所以如果程式上有什麼更好的解法,歡迎提出見解。

這次題目

Given a string s consisting of words and spaces, return the length of the last word in the string.

A word is a maximal substring consisting of non-space characters only.

Example

1
2
3
Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.
1
2
3
Input: s = "   fly me   to   the moon  "
Output: 4
Explanation: The last word is "moon" with length 4.
1
2
3
Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.

Constraints:

  • 1 <= s.length <= 104
  • s consists of only English letters and spaces ' '.
  • There will be at least one word in s.

自已解法

這次的解法就直接先把前後的空白直接消除並且轉換陣列,接著再判斷最後一值是否為空白,是的話返回len-2,否則是len-1

1
2
3
4
5
6
7
8
9
10
var lengthOfLastWord = function(s) {
let strs = s.trim().split(' ');
let len = strs.length;

if (strs[len-1] === '') {
return strs[len - 2].length;
} else {
return strs[len - 1].length;
}
};

之後我參考其他人解法似乎可以完全用函式來處理,不過效能上不太好說(多次提交且比較後,前者會好一點):

1
2
3
4
var lengthOfLastWord = function(s) {
let strTrim = s.trim();
return strTrim.length - strTrim.lastIndexOf(' ') - 1;
};

實作結果

以上就完成了,不過後來看別人解法有更簡單的作法:

Image From LeetCodeImage From LeetCode
Image From LeetCodeImage From LeetCode