剑指offer 5. 替换空格

题目链接

牛客网

题目描述

将一个字符串中的空格替换成 “%20”。

Input:
"A B"

Output:
"A%20B"

解题思路( 考虑从右向左,遇到空格,就填充“20%“,否则将原字符移动应该呆的位置。)

① 在字符串尾部填充任意字符,使得字符串的长度等于替换之后的长度。因为一个空格要替换成三个字符(%20),所以当遍历到一个空格时,需要在尾部填充两个任意字符。
② 令 P1 指向字符串原来的末尾位置,P2 指向字符串现在的末尾位置。P1 和 P2 从后向前遍历,当 P1 遍历到一个空格时,就需要令 P2 指向的位置依次填充 02%(注意是逆序的),否则就填充上 P1 指向字符的值。从后向前遍是为了在改变 P2 所指向的内容时,不会影响到 P1 遍历原来字符串的内容。
③ 当 P2 遇到 P1 时(P2 <= P1),或者遍历结束(P1 < 0),退出。

public String replaceSpace(StringBuffer str) {
    int P1 = str.length() - 1;
    for (int i = 0; i <= P1; i++)
        if (str.charAt(i) == ' ')
            str.append(" ");
    int P2 = str.length() - 1;
    while (P1 >= 0 && P2 > P1) {
        char c = str.charAt(P1--);
        if (c == ' ') {
            str.setCharAt(P2--, '0');
            str.setCharAt(P2--, '2');
            str.setCharAt(P2--, '%');
        } else {
        str.setCharAt(P2--, c);
    }
}
    return str.toString();
}
//我的代码
class Solution {
public:
    void replaceSpace(char *str,int length) {
        if(str==nullptr||length<=0)
            return;
        int space = 0,index;
        for(int i=0;i<length;i++){
            if(*(str+i)==' ')
                ++space;
        }
        index = length + 2*space;
        *(str+index) = '\0';
        index--;
        length--;
        while(length>=0){
            if(*(str+length)==' '){
                *(str+index) = '0';
                *(str+index-1) = '2';
                *(str+index-2) = '%';
                index -= 2;
            }else{
                *(str+index) = *(str+length);
            }
            index--;
            length--;
        }
    }
};
// 利用C++特性
class Solution {
public:
    string replaceSpace(string s) {
        int len = s.length();
        if(len==0)
            return s;
        string res;
        for(const char c:s){
            if(c==' '){
                res += "%20";
            }else{
                res += c;
            }
        }
        return res;
    }
};
  • 时间复杂度:O(n)
  • 空间复杂度:O(1)

本文参考牛客网题解和CS-Notes

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值