zoukankan      html  css  js  c++  java
  • 【嘎】字符串-字符串中的单词数

    题目:

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

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

    示例:

    输入: "Hello, my name is John"
    输出: 5
    解释: 这里的单词是指连续的不是空格的字符,所以 "Hello," 算作 1 个单词。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/number-of-segments-in-a-string

    一开始用了split得到数组的方式,自己又想到了空格变成多个的情况,感觉不对

     emmm然后想到了遍历string

    class Solution {
        public int countSegments(String s) {
            int res = 0;
            boolean flag = false; // 是空的
            if (s != null && s.trim().length() > 0) {
                for (int i = 0; i < s.length(); i++) {
                    char c = s.charAt(i);
                    // 不为空
                    if (String.valueOf(c) != null && (c + "").trim().length() > 0 ) {
                        // 原来为空
                        if (!flag ) {
                            res++;
                        }
                        flag = true;
                    } else {
                        flag = false;
                    }
                }
            }
            return res;
        }
    }

    这种方法好慢:

     后来看到题解中还是有人用split了,然后再遍历一次,将是空格的去掉,那时候的空格肯定都会是 " "

    class Solution {
        public int countSegments(String s) {
            String[] arr = s.split(" ");
            int len = 0;
            for (String t : arr) {
                if (t.equals(" ") || t.isEmpty()){
                    continue;
                }
                len++;
            }
            return len;
        }
    }
    越努力越幸运~ 加油ヾ(◍°∇°◍)ノ゙
  • 相关阅读:
    给自己一个书单
    pureMVC学习之一
    泛型与无聊
    队列与DelphiXe新语法
    有道理的前端
    具备 jQuery 经验的人如何学习AngularJS(附:学习路径)
    Blogging with github Pages
    Cookie/Session机制
    通往全栈工程师的捷径 —— react
    女生应该找个有独立博客的男朋友
  • 原文地址:https://www.cnblogs.com/utomboy/p/12698781.html
Copyright © 2011-2022 走看看