LeetCode刷题--点滴记录005

Posted 鲁棒最小二乘支持向量机

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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();
    


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

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

以上是关于LeetCode刷题--点滴记录005的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode刷题--点滴记录017

LeetCode刷题--点滴记录015

LeetCode刷题--点滴记录003

LeetCode刷题--点滴记录006

LeetCode刷题--点滴记录009

LeetCode刷题--点滴记录001