Skip to content

Latest commit

 

History

History
50 lines (37 loc) · 1.39 KB

58md.md

File metadata and controls

50 lines (37 loc) · 1.39 KB

LeetCode 58. Length of Last Word

##題目 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, Given s = "Hello World", return 5.

##翻譯 給一個字串s,其中包含大小寫字母與空白' ',回傳最後一個單字的長度,如果沒有最後一個單字,回傳0。

注意:單字的定義是由一串連續中間沒空白的字元所組成。

範例: Given s = "Hello World",最後一個單字為world,長度為5。

##思路

  1. 用split把字串拆成陣列,例如 "Hello World " -> ['Hello','World', ' ']
  2. 取陣列最後一個元素,上面範例取出來的是空字串' '
  3. 空字串不是我們要的單字,往前再取到'World',因此最後一個單字長度為5

##解題

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLastWord = function(s) {
    var ary = s.split(/\s/); //使用regex將字串切開
    
    if(s.length == 0) return 0;
    if(ary.length == 0) return 0;
    
    // 從陣列最後面取出單字,如果是空白' '就不是單字,所以繼續往前找
    while(ary.length > 0){
        var v = ary.pop();
        if(v.length > 0){
            return v.length;
        }
  
    }
    
    return 0;
};