版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/85019880
Title:Number of Segments in a String 434
Difficulty:Easy
原题leetcode地址:https://leetcode.com/problems/number-of-segments-in-a-string/
1. 注解见代码注释
时间复杂度:O(n),一次一层for循环,最长遍历整个字符串。
空间复杂度:O(1),没有申请额外空间。
/**
* 当前字符为为“空”,且前一个字符为“空”,注意第一个字符
* @param s
* @return
*/
public static int countSegments(String s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
if ((i == 0 || s.charAt(i - 1) == ' ') && s.charAt(i) != ' ') {
count++;
}
}
return count;
}