LeetCode刷题--点滴记录005

5. 剑指 Offer 05. 替换空格

要求

请实现一个函数,把字符串 s 中的每个空格替换成"%20"。

解题

C++版本
#include <iostream>
using namespace std;

class Solution
{
public:
    string replaceSpace(string s)
    {
        int len = s.size();
        int count = 0;
        //统计空格数量
        for (int i = 0; i < len; i++)
            if (s[i] == ' ')
                count++;
        s.resize(len + count * 2);//修改s长度
        int j = s.size()-1;
        for (int i = len -1; i < j; i--,j--)
        {
            if (s[i] != ' ')
            {
                s[j] = s[i];
            }
            else
            {
                s[j - 2] = '%';
                s[j - 1] = '2';
                s[j] = '0';
                j -= 2;
            }
        }
        return s;
    }
};

void test01()
{
    string s1 = "We are happy.";
    Solution s;
    string s2 = s.replaceSpace(s1);
    for (int i = 0; i < s1.size(); i++)
    {
        cout << s1[i];
    }
    cout << endl;
    for (int i = 0; i < s2.size(); i++)
    {
        cout << s2[i];
    }
    cout << endl;
}

int main()
{
    test01();

    system("pause");
    return 0;
}

在这里插入图片描述

Python版本
class Solution:
    def replaceSpace(self, s: str) -> str:
        res = ""
        for c in s:
            if c == ' ': 
                res += "%20"
            else: 
                res += c
        return res
            
def test01():
    solution = Solution()
    s1 = "We are happy."
    print(s1)
    s2 = solution.replaceSpace(s1)
    print(s2)
    
            
if __name__=="__main__":
    test01()

在这里插入图片描述

Java版本
package com.hailei_01;

public class replaceSpace {
    public static void main(String[] args) {
        String s1 = "We are happy.";
        System.out.println(s1);
        String s2 = replaceSpace01(s1);
        System.out.println(s2);
        String s3 = replaceSpace02(s1);
        System.out.println(s3);
    }

    public static String replaceSpace01(String s) {
        s = s.replace(" ","%20");
        return s;
    }
    public static String replaceSpace02(String s) {
        StringBuilder res = new StringBuilder();
        for(Character c : s.toCharArray())
        {
            if(c == ' ')
                res.append("%20");
            else
                res.append(c);
        }
        return res.toString();
    }

}

在这里插入图片描述

希望本文对大家有帮助,上文若有不妥之处,欢迎指正

分享决定高度,学习拉开差距

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鲁棒最小二乘支持向量机

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值