题目描述:
请实现一个函数,把字符串中的每个空格替换成“%20”。例如,输入“We are happy.”,则输出“We%20are%20happy.”
解题思路:
为了减少时间复杂度,减少字符重复向后移动,把从前向后替换改为从后向前替换。具体实现是通过StringBuffer构建新字符串,通过设置新的长度,将新的index与原来的index进行逐一对应。构造出需要的字符串。
public class MS5 {
public static void main(String[] args) {
String s = "we are happy.";
StringBuffer str = new StringBuffer(" ") ;
int length = s.length();
for (int i = 0; i <s.length() ; i++) {
if (s.charAt(i)==' ')
length+=2;
}
str.setLength(length);
System.out.println(s.length());
int indexofOriginal = s.length()-1;
int indexofNew = length-1;
while(indexofOriginal>=0)
{
if (s.charAt(indexofOriginal)!=' '){
str.setCharAt(indexofNew--,s.charAt(indexofOriginal));
}
else {
str.setCharAt(indexofNew--,'0');
str.setCharAt(indexofNew--,'2');
str.setCharAt(indexofNew--,'%');
}
indexofOriginal--;
}
System.out.println(str.toString());
}
}