Title: Please implement a function that replaces a space in a string with "%20". For example, when the string is Are Happy, the replaced string is We%20are%20happy.
The idea is if you insert from left to right, the time complexity is O (N2), first determine the number of spaces, and then determine the replacement string length, from right to left to insert the time complexity of O (n)
Simple, but highly time-complicated code:
public class Solution {public
String replacespace (StringBuffer str) {return
str.tostring (). ReplaceAll ("\\s", "%20");
}
My Code:
public class Solution {public String replacespace (StringBuffer str) {int originallength = s Tr.length ()-1; String str original length int numberofblank = 0;
Number of spaces//int i = 0;
for (char c:str.tostring (). ToCharArray ()) {if (c = = ") {numberofblank++;
an int newlength = originallength + numberofblank*2+1;
Str.setlength (newlength);
Newlength = newLength-1; while (originallength >= 0 && newlength > Originallength) {if (str.charat) = =
') {Str.setcharat (newlength--, ' 0 ');
Str.setcharat (newlength--, ' 2 ');
Str.setcharat (newlength--, '% ');
}else{Str.setcharat (newlength--, Str.charat (originallength));
} originallength--;
return str.tostring (); }
public static void Main (String args[]) {
StringBuffer str = new StringBuffer ();
Str.append ("HelloWorld");
}