-
-
Save michaelniu/7a44ceae93a42099d10a to your computer and use it in GitHub Desktop.
cc150-1.4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 1.4 Write a method to replace all spaces in a string with'%20'. You may assume that | |
the string has sufficient space at the end of the string to hold the additional | |
characters, and that you are given the "true" length of the string. (Note: if implementing | |
in Java, please use a character array so that you can perform this operation | |
in place.) | |
EXAMPLE | |
Input: "Mr John Smith" | |
Output: "Mr%20Dohn%20Smith" | |
input char[] str | |
Algorithm : | |
1. set lastIndex = trueLength of str, | |
2. from the str end to begin find the space char (str[i]) | |
3 move rest elments for two spaces | |
4, char[i]='%'; char[i+1] = '2' char[i+2]=0; | |
5, lastindex= lastindex+3; | |
O(n^2) space O(1) | |
*/ | |
public class ReplaceSpace_1_4 { | |
public static void main(String[] args) { | |
//assume input string is not null and have enough space to | |
char[] str = {'m','r',' ',' ','m','r',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '}; | |
String result = replaceSpace(str,6); | |
System.out.println(result); | |
str = new char[] {'m','r',' ',' ','m','r','m','r',' ','m','r',' ','m','r',' ','m','r',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '}; | |
result = replaceSpace(str,17); | |
System.out.println(result); | |
str = new char[] {'m','r',' ',' ',' ','m','r','m','r',' ','m','r',' ','m','r',' ','m','r',' ',' ','s','m','i','t','h',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '}; | |
result = replaceSpace(str,25); | |
System.out.println(result); | |
} | |
private static String replaceSpace(char[] str,int truelength) { | |
int indexOfLastNonSpace =truelength; | |
int i=truelength-1; | |
while(i>=0){ | |
if(str[i]==' '){ | |
for(int j=indexOfLastNonSpace-1;j>i;j--){ | |
str[j+2]=str[j]; | |
} | |
str[i]='%'; | |
str[i+1]='2'; | |
str[i+2]='0'; | |
indexOfLastNonSpace+=3; | |
} | |
i--; | |
} | |
return String.valueOf(str); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment