剑指offer 字符串 持续更新中...


持续更新中…

1. 替换空格

替换空格

1.1 题目描述

题目描述:将一个字符串s中的每个空格替换成“%20”。

示例

输入:"We Are Happy"
返回:"We%20Are%20Happy"

1.2 从前向后替换空格

时间复杂度是O(n^2)

#include <string>
class Solution {
    std::string res;        // 要返回的字符串
    int n, blank_cnt;       // res的长度, 空格的个数
  public:
    string replaceSpace(string s) {
        res = s;
        blank_cnt = countBlank(s);
        res.resize(s.size() + blank_cnt * 2);
        n = res.size();
        for (int i = 0; i < n; ++i) {
            if (res[i] == ' ') {
                moveStr(i);
                res[i]     = '%';
                res[i + 1] = '2';
                res[i + 2] = '0';
            }
        }
        return res;
    }

    // 从pos+1开始,将每个字符向后移动两次
    void moveStr(int pos) {
        for (int i = n; i >= pos + 1; --i) {
            res[i + 2] = res[i];
        }
    }

    // 得到空格的个数
    int countBlank(string s) {
        int cnt = 0;
        for (int i = 0; i < s.size(); ++i)
            if (res[i] == ' ')
                cnt++;
        return cnt;
    }
};

1.3 从后向前替换空格

时间复杂度是O(n)

#include <cstddef>
#include <string>
#include <type_traits>
class Solution {
    std::string res;        // 要返回的字符串
    size_t n, blank_cnt;    // res的长度, 空格的个数
    int left, right;        // 左右指针
  public:
    string replaceSpace(string s) {
        res = s;
        blank_cnt = countBlank(s);
        res.resize(s.size() + blank_cnt * 2);
        n = res.size();
        left = s.size(), right = n;
        while (left < right) {
            if (res[left] == ' ') {
                left--;
                res[right--] = '0';
                res[right--] = '2';
                res[right--] = '%';
            } else {
                res[right] = res[left];
                right--, left--;
            }
            if (left == right || left < 0)    break;
        }
        std::cout << res;
        return res;
    }

    // 得到空格的个数
    int countBlank(string s) {
        int cnt = 0;
        for (int i = 0; i < s.size(); ++i)
            if (res[i] == ' ')
                cnt++;
        return cnt;
    }
};

这题88. 合并两个有序数组 - 力扣(LeetCode)与之类似,我们可以得到一个结论:合并两个字符串(包括数组),如果从前往后复制,可能重复移动,那么就可以考虑从后往前复制

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值