字符串中的单词数

题目描述:统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。

请注意,你可以假定字符串里不包括任何不可打印的字符。

示例说明请见LeetCode官网。

解法一:字符串遍历

首先,如果snull或者s为空字符串,则直接返回0。

否则,声明一个count记录单词数量初始化为0,lastChar记录上一个字符初始值为空格字符,然后遍历s中的字符c,处理过程如下:

  • 如果clastChar都是空格,则当前不可能是单词,跳过;
  • 如果上一个字符是空格,当前字符不是空格,则当前字符是一个单词的开始,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, "));
}
}


【每日寄语】 贵在坚持、难在坚持、成在坚持。