劍指offer --- 替換空格

替換空格

題目

請實現一個函數,將一個字符串中的每個空格替換成"%20"。例如,當字符串爲We Are Happy時,經過替換後的字符串爲We%20Are%20Happy

思路

  1. 如果用python的話,直接return s.replace(' ','%20'),假設沒有replace這個函數,自己實現:
  2. 空格是一位,但是%20是三位,如何解決?這個即爲考點,不能每更改一次,後面就挪一次,因此不能在原來的字符串上進行更改,需要新建一個字符串。

python

class Solution(object):
    def replaceSpace(self, s):
        """
        :type s: str
        :rtype: str
        """
        strLen=len(s)
        aaa=[]
        for i in range(strLen-1,-1,-1):
            if s[i]==" ":
                aaa.append("0")
                aaa.append("2")
                aaa.append("%")
            else:
                aaa.append(s[i])
        aaa.reverse()
        return ''.join(aaa)

在這裏插入圖片描述

C++

class Solution {
public:
    string replaceSpace(string s) {
        string str;
        string s1 = "%20";
        for(auto a:s){
            if(a == ' ')
                str = str + s1;
            else
                str = str + a;
        }
        return str;
    }
};  

在這裏插入圖片描述

leetcode該題網址:

https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章