Summary: First calculate the total number of spaces, count++, and then traverse from backward, each encounter a space, count--;Replace spaces
- Number of participants: 2119 time limit: 1 seconds space limit: 32768K
- By scale: 20.23%
- Best record: 0 ms|8552k(from oregano)
Title description Implement a function that replaces a space in a string with "%20". For example, when the string is we are Happy. The string after substitution is we%20are%20happy. Full code:
Public classStringreplacespace { Public Static voidMain (string[] args) {stringbuffer str=NewStringBuffer ("We are Happy"); SYSTEM.OUT.PRINTLN (Replacespace (str)); } Public StaticString replacespace (StringBuffer str) {intCount=0; for(intI=0;i<str.length (); i++){ if(Str.charat (i) = = ") {Count++; } } CharStr2[] =New Char[Str.length () +count*2]; for(intJ=str.length () -1;j>=0;j--){ Chartemp =Str.charat (j); if(temp!= ") {str2[j+2*count] =temp; } Else{str2[j+2*count]= ' 0 '; Str2[j+2*count-1]= ' 2 '; Str2[j+2*count-2]= '% '; Count--; }} stringbuffer Str3=NewStringBuffer (); for(intk=0;k<str2.length;k++) {str3.append (str2[k]); } returnstr3.tostring (); }}
Sword offer--Replacement string