#Leetcode# 434. Number of Segments in a String

Posted 丧心病狂工科女

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了#Leetcode# 434. Number of Segments in a String相关的知识,希望对你有一定的参考价值。

https://leetcode.com/problems/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

代码:

class Solution {
public:
    int countSegments(string s) {
        s += ‘ ‘;
        int len = s.length();
        int ans = 0;
        for(int i = 0; i < len; i ++) {
            if(s[i] == ‘ ‘) continue;
            ans ++;
            while(i < len && s[i] != ‘ ‘) i ++;
        }
        return ans;
    }
};

  遍历字符串 判断空格之间夹的就是单词了 之前做过 HDU 的单词数 和这个差不多啦

FH

以上是关于#Leetcode# 434. Number of Segments in a String的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 434. 字符串中的单词数(Number of Segments in a String)

434. Number of Segments in a String

434. Number of Segments in a String

434. Number of Segments in a String

434. 求字符串有多少段 Number of Segments in a String

Leecode刷题之旅-C语言/python-434 字符串中的单词数