---
# System prepended metadata

title: \#434 Number of Segments in a String
tags: [leetcode, leetcode-easy]

---

# \#434 Number of Segments in a String
## *給定一字串s, 回傳s內有幾個讀單字片段(由連續的英文字母組成, 並且由空白間隔)*
## Log
 - build 20210816 by syhuang

## 另解
 - 一個字元一個字元跑迴圈判斷
 - 沒比較快,占空間也較多
 - leetcode submit runtime 60%, memory 6%
```javascript=
var countSegments = function(s) {
    let result = 0;
    for(let i=0; i<s.length; i++){
        if(s.charAt(i)!=' ' && (i==0 || s.charAt(i-1)==' ')) result++;
    }
    return result
};
```
## 初見
 - split + filter(去掉空字串不算片段)應用
 - edge case:空字串片段
 - leetcode submit runtime 80%, memory 20%
```javascript=
var countSegments = function(s) {
    let t = s.split(' ').filter(function(val){
        return val.length > 0;
    });
    return t.length;
};
```
## 備註
## 參考
###### tags: `leetcode`, `leetcode-easy`