[LeetCode] Number of Segments in a String
Posted immjc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 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
找出一个字符串中的单词片段,简单来说就是求一个字符串中的单词数,因为每两个单词由一个空格符隔开,所以单词片段数 = 空格符数 + 1,首先在字符串尾添加一个空格,然后遍历字符串返回空格符数即可。
class Solution { public: int countSegments(string s) { int res = 0; s.push_back(‘ ‘); for (int i = 1; i != s.size(); i++) if (s[i] == ‘ ‘ && s[i - 1] != ‘ ‘) res++; return res; } }; // 3 ms
以上是关于[LeetCode] Number of Segments in a String的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode(191):Number of 1 Bits
Leetcode 200. Number of Islands
LeetCode 191. Number of 1 Bits
LeetCode191 Number of 1 Bits. LeetCode231 Power of Two. LeetCode342 Power of Four