字符串中的单词数
题目形容:统计字符串中的单词个数,这里的单词指的是间断的不是空格的字符。
请留神,你能够假设字符串里不包含任何不可打印的字符。
示例阐明请见LeetCode官网。
起源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl…
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。
解法一:字符串遍历
首先,如果s为null或者s为空字符串,则间接返回0。
否则,申明一个count记录单词数量初始化为0,lastChar记录上一个字符初始值为空格字符,而后遍历s中的字符c,处理过程如下:
- 如果c和lastChar都是空格,则以后不可能是单词,跳过;
- 如果上一个字符是空格,以后字符不是空格,则以后字符是一个单词的开始,count加一,并且将lastChar更新为以后字符;
- 如果上一个字符和以后字符都不是空格,则跳过;
- 如果上一个字符不是空格,而以后字符是空格,则上一个字符是上一个单词的最初一个字符。将lastChar更新为以后字符。
最初,返回count即为字符串s中的单词数。
/**
* @Author: ck
* @Date: 2021/9/29 8:51 下午
*/
public class LeetCode_434 {
public static int countSegments(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int count = 0;
char lastChar = ' ';
for (char c : s.toCharArray()) {
if (lastChar == ' ' && c == ' ') {
// 如果上一个字符和以后字符都是空格,则跳过
continue;
} else if (lastChar == ' ' && c != ' ') {
// 如果上一个字符是空格,以后字符不是空格,则以后字符是一个单词的开始,count加一,并且将lastChar更新为以后字符
lastChar = c;
count++;
} else if (lastChar != ' ' && c != ' ') {
// 如果上一个字符和以后字符都不是空格,则跳过
continue;
} else if (lastChar != ' ' && c == ' ') {
// 如果上一个字符不是空格,而以后字符是空格,则上一个字符是上一个单词的最初一个字符。将lastChar更新为以后字符
lastChar = c;
}
}
return count;
}
public static void main(String[] args) {
// 冀望输入: 5
System.out.println(countSegments("Of all the gin joints in all the towns in all the world, "));
}
}
【每日寄语】 贵在保持、难在保持、成在保持。
发表回复