学而不思则罔,思而不学则殆
题目
- 题目:实现一个算法,把字符串中的每个空格替换成“%20”
- 例如:We are happy.
- 则输出:We%20are%20happy.
算法
思路:双指针,从后往前
一个空格符替换成成"%20",因此数组长度增减为空格符的个数*2
时间复杂度: O ( n ) O(n) O(n)
//思路:双指针,从后往前
static String replace(char[] chars) {
if (chars == null) {
return null;
}
//计算空格数量
int nullCharNum = 0;
for (char aChar : chars) {
if (aChar == ' ') {
nullCharNum++;
}
}
//定义新的数组长度
char[] newChar = new char[chars.length + nullCharNum * 2];
int newCharIndex = newChar.length - 1;
for (int oldCharIndex = chars.length - 1; oldCharIndex >= 0; oldCharIndex--) {
char ch = chars[oldCharIndex];
if (ch == ' ') {//填充“%20”
newChar[newCharIndex--] = '0';
newChar[newCharIndex--] = '2';
newChar[newCharIndex--] = '%';
} else {
//填充字符
newChar[newCharIndex--] = ch;
}
}
return new String(newChar);
}
测试
public static void main(String[] args) {
String test = "We are happy.";
System.out.println(test);
String replace = replace(test.toCharArray());
System.out.println(replace);
test = "String replace = replace(test.toCharArray());";
System.out.println(test);
replace = replace(test.toCharArray());
System.out.println(replace);
test = "String replace";
System.out.println(test);
replace = replace(test.toCharArray());
System.out.println(replace);
test = "Stringreplace";
System.out.println(test);
replace = replace(test.toCharArray());
System.out.println(replace);
}
输出如下:
We are happy.
We%20are%20happy.
String replace = replace(test.toCharArray());
String%20replace%20=%20replace(test.toCharArray());
String replace
String%20%20%20replace
Stringreplace
Stringreplace