标签:
Write a method to replace all spaces in a string with %20
. The string is given in a characters array, you can assume it has enough space for replacement and you are given the true length of the string.
Given "Mr John Smith"
, length = 13
.
The string after replacement should be "Mr%20John%20Smith"
.
If you are using Java or Python,please use characters array instead of string.
Do it in-place.
\\\\\\First, find out how many spaces there are, add 2 extra length to the original length.
record the new length of the return string.
\\\\ Then, keep tracking the string from the end to start.
\\\\ When there is a space, set them to 02%
public class Solution { /** * @param string: An array of Char * @param length: The true length of the string * @return: The true length of new string */ public int replaceBlank(char[] string, int length) { // Write your code here if(length==0) return 0; int len=length; for(int i=0;i<length;i++) { if(string[i]==‘ ‘) { len=len+2; } } int res=len; string[len]=‘\0‘; --len; for(int i=length-1;i>=0;i--) { if(string[i]==‘ ‘) { string[len--]=‘0‘; string[len--]=‘2‘; string[len--]=‘%‘; } else { string[len--]=string[i]; } } return res; } }
[lintcode easy]Space Replacement
标签:
原文地址:http://www.cnblogs.com/kittyamin/p/4990417.html