• LeetCode-434-字符串中的单词数


    字符串中的单词数

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

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

    示例说明请见LeetCode官网。

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

    解法一:字符串遍历

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

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

  • 相关阅读:
    从体制内的国家干部转变为自由职业者-2017年总结
    为什么选择Django?
    Django contrib Comments 评论模块详解
    Django 2.0 新特性 抢先看!
    Python 为何能坐稳 AI 时代头牌语言
    为什么说Python 是大数据全栈式开发语言
    继承中的构造方法
    super关键字
    方法的重写
    类的继承与访问控制
  • 原文地址:https://www.cnblogs.com/kaesar/p/15391674.html
Copyright © 2020-2023  润新知