【剑指 Offer 05】 替换空格

【剑指 Offer 05】 替换空格

题目描述:

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/

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

示例:

  • 示例1:
输入:s = "We are happy."
输出:"We%20are%20happy."
  • 提示:
            0 <= s 的长度 <= 10000
  • 相关用法题目:

《剑指offer–58-1.翻转单词顺序》.

代码(python3)

解析思路:简单来说,直接用python的内置函数


class Solution:
    def replaceSpace(self, s: str) -> str:
        s = s.split(' ');
        s = '%20'.join(s)
        
        return s

代码(c++)

解析思路: 基本的查找替换思想


class Solution {
    
    
public:
    string replaceSpace(string s) {
    
    
        string array; // 存储结果

        for (auto &c : s){
    
     // 遍历原字符串
            if(c == ' '){
    
    
                array += "%20";
            }
            else{
    
    
                array += c ;
            }

        }
    return array;
    }
};



Guess you like

Origin blog.csdn.net/Kefenggewu_/article/details/121125071