关于java:LeetCode434字符串中的单词数

6次阅读

共计 1144 个字符,预计需要花费 3 分钟才能阅读完成。

字符串中的单词数

题目形容:统计字符串中的单词个数,这里的单词指的是间断的不是空格的字符。

请留神,你能够假设字符串里不包含任何不可打印的字符。

示例阐明请见 LeetCode 官网。

起源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl…
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。

解法一:字符串遍历

首先,如果 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,"));
    }
}

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

正文完
 0