zoukankan      html  css  js  c++  java
  • 434. Number of Segments in a String 字符串中的单词个数

    [抄题]:

    Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.

    Please note that the string does not contain any non-printable characters.

    Example:

    Input: "Hello, my name is John"
    Output: 5

     [暴力解法]:

    时间分析:

    空间分析:

     [优化后]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    第一位只会是单词,不会是空格

    [思维问题]:

    以为从空格开始数,计算单词数

    [一句话思路]:

    一般都是正面思考,直接数单词就行

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    正面思考就行

    [复杂度]:Time complexity: O(n) Space complexity: O(1)

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    [关键模板化代码]:

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

    class Solution {
        public int countSegments(String s) {
            //cc
            if (s.length() == 0) {
                return 0;
            }
            //ini
            int ans = 0;
            
            //for loop
            for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' ')) {
                    ans++;
                }
            }
            
            //return
            return ans;
        }
    }
    View Code

     [代码风格] :

  • 相关阅读:
    创建异步Web服务
    MCAD考试计划
    微软面试题
    Reborn
    Qt项目注意事项
    在ASP.Net中两种利用CSS实现多界面
    为ASP.NET控件添加常用的JavaScript操作
    用Split函数分隔字符串
    Microsoft .NET Pet Shop 4.0
    搞定QString,string,char*,CString的互转
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8648663.html
Copyright © 2011-2022 走看看