![微信公众号:路人zhang](https://image.mianshi.online/img202209102100234.png)
扫码关注微信公众号
回复“面试手册”,获取本站PDF版
回复“简历”,获取高质量简历模板
回复“加群”,加入程序员交流群
回复“电子书”,获取程序员类电子书
题目描述
请实现一个函数,把字符串 s 中的每个空格替换成”%20″。
示例 1:
输入:s = "We are happy."
输出:"We%20are%20happy."
限制:
0 <= s 的长度 <= 10000
题解
(模拟) O(n)
创建一个答案字符串 res,遍历原字符串,如果是空格则加 %20
,否则加当前字符。
时间复杂度
O(n)
空间复杂度
O(n)
C++ 代码
class Solution {
public:
string replaceSpace(string s) {
string res;
for (auto c : s)
if (c == ' ') res += "%20";
else res += c;
return res;
}
};
Java 代码
class Solution {
public String replaceSpace(String s) {
StringBuilder res = new StringBuilder();
for (char c : s.toCharArray()) {
if (c == ' ') {
res.append("%20");
} else {
res.append(c);
}
}
return res.toString();
}
}
Python 代码
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)
本文由读者提供,Github地址:https://github.com/tonngw
点击面试手册,获取本站面试手册PDF完整版