Scanning

题目描述[原题描述][https://www.acwing.com/problem/content/description/17/]

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

你可以假定输入字符串的长度最大是1000。
注意输出字符串的长度可能大于1000。

样例

1
2
3
输入:"We are happy."

输出:"We%20are%20happy."

算法描述

遍历字符串,统计' '的个数,更新字符串的长度,做完初始化操作后,从字符串,后面开始遍历旧字符串,不等于空格,将单个字符添加到新字符串后边,等于' '时,依次添加'0','2','%',直到遍历完字符串;

C++代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
string replaceSpaces(string &str) {
int len = 0;
for(auto c : str){
if(c == ' ')
len+=3;
else len++;
}
int i=str.length()-1;
str.resize(len);
int j = len-1;
while(i>=0){
if(str[i]==' '){
str[j--]='0';
str[j--]='2';
str[j--]='%';
}else str[j--]=str[i];
i--;
}
return str;
}
};

Java代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//解法一
class Solution {
public String replaceSpaces(StringBuffer str) {
String s = "%20";
String st = str.toString();
return st.replace(" ",s);
}
}
//解法二
class Solution {
public String replaceSpaces(StringBuffer str) {
int count = 0;
int length = str.length();
int t = length;
for(int i =0 ;i<length;i++){
if(str.charAt(i) == ' ')count++;
}
t+=count*2;
str.setLength(t);
for(int l = length-1,ll = t-1;l>=0&&t>0;l--){
if(str.charAt(l)==' '){
str.setCharAt(ll--,'0');
str.setCharAt(ll--,'2');
str.setCharAt(ll--,'%');
t--;
}else str.setCharAt(ll--,str.charAt(l));
}
return str.toString();
}
}