LeetCode 434. Number of Segments in a String
考点 | 难度 |
---|---|
String | Easy |
题目
You are given a string s
, return the number of segments in the string.
A segment is defined to be a contiguous sequence of non-space characters.
思路
判断第i
位不是空格且i-1
位是空格,满足加一。
答案
public int countSegments(String s) {
int segmentCount = 0;
for (int i = 0; i < s.length(); i++) {
if ((i == 0 || s.charAt(i-1) == ' ') && s.charAt(i) != ' ') {
segmentCount++;
}
}
return segmentCount;
}