剑指 Offer 05. 替换空格【字符串】

题目描述

请实现一个函数,把字符串 s 中的每个空格替换成”%20”。

示例 1:

输入:s = “We are happy.”
输出:”We%20are%20happy.”

限制:

0 <= s 的长度 <= 10000

解题思路

遍历整个字符串,遇到空格时,向StringBuilder对象 加入”%20”,其他情况正常加入即可。最后将结果转换成String对象

代码实现

1
2
3
4
5
6
7
8
9
10
11
public String replaceSpace(String s) {
StringBuilder sb=new StringBuilder();
for(int i=0;i<s.length();i++){
if(s.charAt(i)==' '){
sb.append("%20");
}else{
sb.append(s.charAt(i));
}
}
return sb.toString();
}

复杂度分析

时间复杂度 O(n)

空间复杂度 O(n)

资源

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

剑指 Offer 05. 替换空格【字符串】

http://example.com/2021/03/27/05 替换空格/

Author

John Doe

Posted on

2021-03-27

Updated on

2021-06-08

Licensed under

You need to set install_url to use ShareThis. Please set it in _config.yml.
You forgot to set the business or currency_code for Paypal. Please set it in _config.yml.

Comments

You forgot to set the shortname for Disqus. Please set it in _config.yml.