算法题(1)- 字符串去空格

1 题目描述

  用熟悉的语言写一个函数,把字符串里面的空格全部去掉,

  并返回删除的空格的个数,不允许开辟空间,只能申请简单类型的自动变量

  要求时间复杂度 O(n)

  Time Complexity : O(n)

  Space Complexity : O(1)

  2 解题源码

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

class Solution {
public:
    static int DeleteWhiteSpace(string &s) {
        int res = 0;

        if (s.size() <= 0)
            return 0;

        auto st = s.begin();
        auto cur = st;

        while (cur != s.end()) {
            if (isspace(*cur)) {
                res++;
                cur++;
            }
            else {
                *st = *cur;
                cur++;
                st++;
            }
        }
        s.erase(st, s.end());
        return res;
    }
};

void test(string & test_string) {
    cout << "original input s=" << "\"" << test_string << "\"" << endl;
    cout << "count of WhiteSpace(s) is " << Solution::DeleteWhiteSpace(test_string) << endl;
    cout << "after delete white space(s) s=" << "\"" << test_string << "\"" << endl;
}


int main() {
    string s1 = " a b c  ";
    string s2 = " a b  c";
    string s3 = "";
    test(s1);
    test(s2);
    test(s3);

    return 0;
}

3 总结

现实中遇到这个问题,用 STL + string 类的 find 及 substr/str 等成员函数即可实现题目的解答。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值