题目描述:
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.
You code should also return the new length of the string after replacement.
If you are using Java or Python,please use characters array instead of string.
Have you met this question in a real interview? Yes ExampleGiven "Mr John Smith", length = 13.
The string after replacement should be "Mr%20John%20Smith", you need to change the string in-place and return the new length 17.
ChallengeDo it in-place.
题目思路:既然要做in-place work,那么我们首先要知道new length是多长,这样我们可以找到新string的尾巴在哪里,然后从尾巴开始做新的string,就可以做到in-place了。求新的length也很简单,先从旧的string计算一共有多少个space,然后new length = length + 2 * num of spaces就可以了。
Mycode(AC = 12ms):
class Solution { public: /** * @param string: An array of Char * @param length: The true length of the string * @return: The true length of new string */ int replaceBlank(char string[], int length) { // Write your code here // get the number of spaces int num_space = 0; for (int i = 0; i < length; i++) { if (string[i] == ' ') { num_space++; } } // get new length according to number of spaces int new_length = length + num_space * 2; int r = length - 1; // starting from end of new string for (int i = new_length - 1; i >= 0; i--) { if (string[r] == ' ') { string[i] = '0'; string[i - 1] = '2'; string[i - 2] = '%'; i -= 2; } else { string[i] = string[r]; } r--; } return new_length; } };