剑指 Offer 05. 替换空格
请实现一个函数,把字符串
s中的每个空格替换成"%20"。
示例 1:
输入:s = "We are happy."
输出:"We%20are%20happy."
限制:
0 <= s 的长度 <= 10000
- 利用c++ STL string的特性进行简单的模拟即可
| C++版本 |
class Solution {
public:
string replaceSpace(string s) {
string res;
for(auto ch:s){
if(ch==' '){
res += "%20";
}else{
res += ch;
}
}
return res;
}
};
| Python版本 |
class Solution:
def replaceSpace(self, s: str) -> str:
return s.replace(" ","%20")
该篇博客探讨了如何使用C++和Python实现将字符串中的空格替换为%20的功能。通过STLstring特性和字符串操作,代码简洁高效,适用于处理长度不超过10000的字符串。
1780

被折叠的 条评论
为什么被折叠?



