1: The theme of the program
1. Topic
Please implement a function to replace spaces in a string with "%20". For example, when the string is We Are Happy., the replaced string is We%20Are%20Happy.
2. My program
1 package com.jianke.it; 2 3 public class ReplaceSpace { 4 5 public static void main(String[] args) { 6 StringBuffer str=new StringBuffer("We Are Happy"); 7 String result=replaceSpace(str); 8 System.out.println(result); 9 } 10 public static String replaceSpace(StringBuffer str) { 11 StringBuffer str2=new StringBuffer(); 12 int len=str.length(); 13 for(int i=0;i<len;i++) { 14 if(str.charAt(i)!=' ') { 15 str2.append(str.charAt(i)); 16 }else { 17 str2.append("%20"); 18 } 19 } 20 21 return str2.toString(); 22 } 23 24 }
3. Effects
4. Procedure 2
问题1:替换字符串,是在原来的字符串上做替换,还是新开辟一个字符串做替换!
问题2:在当前字符串替换,怎么替换才更有效率(不考虑java里现有的replace方法)。
从前往后替换,后面的字符要不断往后移动,要多次移动,所以效率低下
从后往前,先计算需要多少空间,然后从后往前移动,则每个字符只为移动一次,这样效率更高一点。
Conclusion: My method is to open up a new string, this method is to modify the original basis.
1 package com.jianke.it; 2 3 public class ReplaceSpace { 4 5 public static void main(String[] args) { 6 StringBuffer str=new StringBuffer("We Are Happy"); 7 String result=replaceSpace(str); 8 System.out.println(result); 9 } 10 public static String replaceSpace(StringBuffer str) { 11 //spacenum为计算空格数 12 int spacenum = 0; 13 for( int i=0;i<str.length();i++ ){ 14 if (str.charAt(i)==' ' ) 15 spacenum++ ; 16 } 17 // indexold is the str subscript 18 int before replacement indexold = str.length()-1 ; 19 // Calculate the str length 20 after the space is converted into %20 int newlength = str.length() + spacenum*2 ; 21 // indexold is after replacing the space with %20 The str subscript 22 int indexnew = newlength-1 ; 23 // Expand the length of str to the length after converting to %20 to prevent the subscript from going out of bounds 24 str.setLength(newlength); 25 for(;indexold>=0 && indexold<newlength;--indexold){ 26 if(str.charAt(indexold) == ' '){ 27 str.setCharAt(indexnew--, '0'); 28 str.setCharAt(indexnew--, '2'); 29 str.setCharAt(indexnew--, '%'); 30 }else{ 31 str.setCharAt(indexnew--, str.charAt(indexold)); 32 } 33 } 34 return str.toString(); 35 } 36 37}
5. Analysis
&& indexold<newlength
Mainly analyze this condition, if not, it will not be a problem, but why should it be added now.
I thought about it, it's like this:
If the following spaces have been added, and the indexold and indexnew are the same at this time, do not move any more, and the time complexity can be reduced.