1. 程式人生 > 其它 >劍指Offer之替換空格

劍指Offer之替換空格

替換空格

題目描述

請實現一個函式,把字串 s 中的每個空格替換成"%20"。

示例 1:

輸入:s = “We are happy.”
輸出:“We%20are%20happy.”

限制:

0 <= s 的長度 <= 10000

解題思路

建立新的字串,遍歷所給的字串s如果遇到空格就在新建的字串中加‘%20’,如果不是空格就照抄。

程式碼示範

class Solution {
public:
    string replaceSpace(string s) {
        string str;
        for (char c : s) {
            if (c == ' ') {
                str.push_back('%');
                str.push_back('2');
                str.push_back('0');                
            } else {
                str.push_back(c);
            }
        }
        return str;
    }
};

結果

在這裡插入圖片描述

總結

這道題難度低,主要考察是對string的一些函式是否熟悉。

剛開始刷leetcode,也是從簡單的題目入手,希望各位大佬勿噴。