Saturday, June 27, 2015

Space Replacement


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.
Have you met this question in a real interview?
Yes
Example
Given "Mr John Smith", length = 13.
The string after replacement should be "Mr%20John%20Smith".
Note
If you are using Java or Python,please use characters array instead of string.

Challenge
Do it in-place.
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(string == null || length <= 0) return 0;
        int spaceCount = 0;
        for(char c : string){
            if(c == ' ') spaceCount+=2;
        }
        int lastIdx = length + spaceCount - 1;
        for(int i = length - 1; i >= 0; i--){
            if(string[i] == ' '){
                string[lastIdx--] = '0';
                string[lastIdx--] = '2';
                string[lastIdx--] = '%';
            }else{
                string[lastIdx--] = string[i];
            }
        }
        return length + spaceCount;
       
    }
}

2 comments:

  1. I don't understand how this works.. Can you really access an index that is outside of your array bounds? For example if your array was size 3, you shouldn't be able to access array[4]. But this somehow works for the lintcode compiler although it doesn't work for eclipse compiler.

    ReplyDelete
    Replies
    1. Actually I figured it out, it's because LintCode gives us a character array that is larger in size with "enough space for replacement" so string.size is actually much larger than length.

      Delete