字符串中的单词数

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

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

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-segments-in-a-string/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:字符串遍历

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

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

  • 如果c和lastChar都是空格,则当前不可能是单词,跳过;
  • 如果上一个字符是空格,当前字符不是空格,则当前字符是一个单词的开始,count加一,并且将lastChar更新为当前字符;
  • 如果上一个字符和当前字符都不是空格,则跳过;
  • 如果上一个字符不是空格,而当前字符是空格,则上一个字符是上一个单词的最后一个字符。将lastChar更新为当前字符。

最后,返回count即为字符串s中的单词数。

  1. /**
  2. * @Author: ck
  3. * @Date: 2021/9/29 8:51 下午
  4. */
  5. public class LeetCode_434 {
  6. public static int countSegments(String s) {
  7. if (s == null || s.length() == 0) {
  8. return 0;
  9. }
  10. int count = 0;
  11. char lastChar = ' ';
  12. for (char c : s.toCharArray()) {
  13. if (lastChar == ' ' && c == ' ') {
  14. // 如果上一个字符和当前字符都是空格,则跳过
  15. continue;
  16. } else if (lastChar == ' ' && c != ' ') {
  17. // 如果上一个字符是空格,当前字符不是空格,则当前字符是一个单词的开始,count加一,并且将lastChar更新为当前字符
  18. lastChar = c;
  19. count++;
  20. } else if (lastChar != ' ' && c != ' ') {
  21. // 如果上一个字符和当前字符都不是空格,则跳过
  22. continue;
  23. } else if (lastChar != ' ' && c == ' ') {
  24. // 如果上一个字符不是空格,而当前字符是空格,则上一个字符是上一个单词的最后一个字符。将lastChar更新为当前字符
  25. lastChar = c;
  26. }
  27. }
  28. return count;
  29. }
  30. public static void main(String[] args) {
  31. // 期望输出: 5
  32. System.out.println(countSegments("Of all the gin joints in all the towns in all the world, "));
  33. }
  34. }

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