---
# System prepended metadata

title: \#58 Length of Last Word
tags: [leetcode, leetcode-easy]

---

# \#58 Length of Last Word
## *給定字串s, 回傳s的最後一個單字的長度*
## Log
 - build 20210405 by syhuang

## 嘗試用一般邏輯下去解, 速度有變快
 - 從句子尾端開始計算"連續非空白的字元組成"長度
```javascript=
var lengthOfLastWord = function(s) {
    if(s.length==0) return 0;
    var lastWordLen = 0;
    var endWithSpaceFlag = true;
    for(var i=s.length-1; i>=0; i--){
        if(s.charAt(i)!==' ') endWithSpaceFlag = false;
        if(!endWithSpaceFlag){
            if(s.charAt(i)==' ') break;
            lastWordLen++;
        }
    }
    return lastWordLen;
};
```
## 初見
 - javascript的.trim()/.split()方法把句子切成單字陣列, 注意edge case即可, 但發現速度相較其他人的答案有點慢
```javascript=
var lengthOfLastWord = function(s) {
    var sary = s.trim().split(' ');
    return sary.length>0?sary[sary.length-1].length:0;
};
```
## 備註
## 參考
###### tags: `leetcode`, `leetcode-easy`