例如,"we are happy"替换为"we%20are%20happy"。首先,从前往后遍历数组,每次遇到空格,将后边所有元素后移2位,这种算法是不实用的,因为如果存在n个空格,那算法复杂度就是O(n^2)。考虑从后往前遍历数组,就可以避免重复移动,将复杂度降低为O(n).
public class ReplaceAllWhiteSpace {
public static char[]replaceAllWhiteSpace(char[] str) {
if(str ==null || str.length ==0){
return str;
}
//遍历字符数组,计算有多少个空格whiteSpaceCount
int whiteSpaceCount =0;
for(int i =0; i < str.length; i++){
if(str[i] ==32){
whiteSpaceCount++;
}
}
if(whiteSpaceCount ==0) {
return str;
}
//新数组大小为oldSize + whiteSpaceCount * 2
char[] newStr =new char[str.length + whiteSpaceCount *2];
//将旧数组辅助到新数组中
int p1 = str.length -1;
int p2 = newStr.length -1;
while (p1 >=0){
if(str[p1] !=32){
newStr[p2] = str[p1];
}else{
newStr[p2] ='0';
newStr[--p2] ='2';
newStr[--p2] ='%';
}
--p1;
--p2;
}
return newStr;
}
public static void main(String[] args){
char[] arr = {'w','e', ' ', 'a', 'r', 'e', ' ','h','a','p','p','y'};
char[] newArr =replaceAllWhiteSpace(arr);
int begin =0;
while(begin < newArr.length){
System.out.println(newArr[begin++]);
}
}
}
网友评论