Solution One: Time complexity O (n^2)
Workaround Two: The time complexity is O (n)
Code implementation:
Packagestring; Public classSpaceStringReplace2 {//len Total capacity for an array size Public Static void Spacereplace(String Strold,intLen) {Char[] CHS =New Char[Len];Char[] ch = strold.tochararray (); for(inti =0; i < ch.length; i++) {Chs[i] = Ch[i]; }intStroldlen =0;intBlackstring =0;if(chs==NULL|| len<=0) {NewNullPointerException (); }intI=0; while(chs[i]!=' + ') {stroldlen++;if(chs[i]=="') {blackstring++; } i++; }//Convert the space to the length of the% 20 character intStrnewlen = Stroldlen + blackstring*2;if(Strnewlen>len) {NewArrayIndexOutOfBoundsException (); }intIndexofold=stroldlen;//point to '/ ' intIndexofnew=strnewlen; while(indexofold>0&& indexofnew>indexofold) {if(Chs[indexofold] = ="') {chs[indexofnew--] =' 0 '; chs[indexofnew--] =' 2 '; chs[indexofnew--] ='% '; }Else{chs[indexofnew--] = Chs[indexofold]; }--indexofold; } for(CharC:chs) {if(c==' + '){ Break; } System. out. print (c); } System. out. println (); } Public Static void Main(string[] args) {//stringbuilder str = new StringBuilder ("We are happy."); LongTimelast = System.currenttimemillis (); String str ="We are happy."; Spacereplace (str, -);//we%20are%20happy. LongTimeafter = System.currenttimemillis (); System. out. println (Timeafter-timelast); }}
Solution Three:
the JDK's own string segmentation
Code implementation:
Packagestring; Public classSpacestringreplace { Public StaticStringSpacereplace(String strold) {string[] split = Strold.split (" "); StringBuilder StringBuilder =NewStringBuilder (); for(inti =0; I < split.length-1; i++) {stringbuilder.append (Split[i]). Append ("%20"); } stringbuilder.append (split[split.length-1]); String strnew = stringbuilder.tostring ();returnstrnew; } Public Static void Main(string[] args) {//stringbuilder str = new StringBuilder ("We are happy.");String str ="We are happy."; System. out. println (Spacereplace (str));//we%20are%20happy.}}
Space substitution problem in strings (Java edition)