替換空格
題目
請實現一個函數,將一個字符串中的每個空格替換成"%20"。例如,當字符串爲We Are Happy時,經過替換後的字符串爲We%20Are%20Happy
思路
- 如果用python的話,直接
return s.replace(' ','%20')
,假設沒有replace
這個函數,自己實現: - 空格是一位,但是%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/