[Leetcode] 434. Number of Segments in a String 解题报告

本文介绍了一种算法,用于计算字符串中非空格字符组成的连续序列的数量。特别地,该算法能够处理各种特殊情况,如字符串中存在多个连续空格或字符串开头和结尾处的空格。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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

思路

一道练手的题目。需要注意你的代码可以覆盖各种特殊情况(例如字符串中含有两个相邻的空格,以及字符串的开头和末尾有空格等等)。算法的时间复杂度是O(n),空间复杂度是O(1),其中n是字符串的长度。

代码

class Solution {
public:
    int countSegments(string s) {
        int ret = 0;
        bool start = false;
        for (auto c : s) {
            if (c == ' ') {
                if (start) {                // a segment ended
                    ++ret, start = false;
                }
            }
            else {
                if (!start) {               // a segment started
                    start = true;
                }
            }
        }
        if (start) {                        // a segment ended at the end
            ++ret;
        }
        return ret;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值