題目描述:
請(qǐng)實(shí)現(xiàn)一個(gè)函數(shù)牙捉,把字符串 s 中的每個(gè)空格替換成"%20"。
示例 1:
輸入:s = "We are happy."
輸出:"We%20are%20happy."
限制:
0 <= s 的長(zhǎng)度 <= 10000
思路1:
1芬位、二分法先找到右邊界带到;
2、二分法再找到左邊界晌纫;
3永丝、最終返回結(jié)果ans;
Java解法:
class Solution {
public String replaceSpace(String s) {
int len = s.length();
StringBuilder res = new StringBuilder();
for(int i = 0; i < len; i++)
{
if(s.charAt(i) == ' ')
{
res.append("%20");
}else{
res.append(s.charAt(i));
}
}
return res.toString();
}
}
python3解法:
class Solution:
def replaceSpace(self, s: str) -> str:
res = []
for c in s:
if c == ' ' : res.append("%20")
else : res.append(c)
return "".join(res)
來(lái)源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof