题目描述
请实现一个函数,将一个字符串中的每个空格替换成“ ”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We Are Happy。
解题思想
1 .暴力破解 . 遇到空格就将后面字符全部向后移动,这样会造成重复移动的问题,时间复杂度O(n2) 2.首先将字符串中的空格个数计算出来,然后将原来的字符串长度增长,从末尾开始进行遍历,遇到空格就替换,其他元素就复制,直至结束.整个过程仅仅遍历了一次,因而时间复杂度为O(n).
代码实现:
public static int getNum(StringBuffer str
) {
int num
= 0;
for (int i
= 0; i
< str
.length(); i
++) {
if (str
.charAt(i
) == ' ') {
num
+= 1;
}
}
return num
;
}
public static String
replaceSpace(StringBuffer str
) {
int oldLength
= str
.length()-1;
int newLength
= str
.length() + getNum(str
)*2;
str
.setLength(newLength
);
newLength
= newLength
- 1;
while (oldLength
> -1 ) {
if (str
.charAt(oldLength
) == ' ') {
str
.setCharAt(newLength
--, '0');
str
.setCharAt(newLength
--, '2');
str
.setCharAt(newLength
--, '%');
} else {
str
.setCharAt(newLength
--, str
.charAt(oldLength
));
}
oldLength
--;
}
return str
.toString();
}