3
\$\begingroup\$

Problem statement (extracted from cracking the coding interview):

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"

My Solution:

public class InterviewMain {

    public static void main(String[] args){

        //Q 1.4
        String str = "Example String with spaces           ";
        replaceSpaces(str);
    }

    public static void replaceSpaces(String str){

        int trueLength = getTrueLength(str);

        char[] strChar = str.toCharArray();
        int spaceCount = 0;
        int finalLength;

        //count the number of spaces in the original string
        for (int i=0; i<trueLength; i++){
            if (strChar[i]== ' ')spaceCount++;
        }

        //get the length of final char array
        finalLength = trueLength + spaceCount*2;
        char[] finalArr = new char[finalLength];

        //update final array here
        int spaces = 0;
        char temp;
        int index;

        for (int i=0; i < trueLength; i++){
            temp = strChar[i];

            if (temp==' '){
                finalArr[getInsertIndex(i,spaces)]= '%';
                finalArr[getInsertIndex(i+1,spaces)] = '2';
                finalArr[getInsertIndex(i+2,spaces)] = '0';
                spaces++;
                continue;
            }

            index = getInsertIndex(i,spaces);
            finalArr[index] = temp;
        }

        //print results here
        for (int i=0; i < finalLength; i++){
            System.out.print(finalArr[i]);
        }
    }

    private static int getTrueLength(String str) {
        int count=0;
        int length = str.length();
        char[] strChar = str.toCharArray();

        //backtrack from end of string to count padding
        for (int i=length-1; i >=0; i--){
            if (strChar[i]!= ' ')break;
            count++;
        }
        return length-count;
    }

    private static int getInsertIndex(int i, int spaces){
        return (i + spaces*2);
    }
}

I was wondering if someone could review this and point out what I have done right and where I can improve upon. Thank you

\$\endgroup\$
1

2 Answers 2

9
\$\begingroup\$

It's important to pay attention to every bit of detail in the problem description:

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.)

As you're implementing this in Java, your method should receive a char[] instead of a String. And if I interpret correctly, the "true" length is the length without the padding, and is an additional parameter, giving the signature:

void replaceSpaces(char[] input, int trueLength) { ... }

With this established, the implementation can be simplified:

  • No need for getTrueLength: it's a given
  • No need for calculating the final size, it's given by input.length
    • As @rolfl pointed out, the size of input is not 100% clear. The description only states that it has sufficient space. So indeed, we may need to calculate the final size.
  • The printing is unnecessary and should be removed, as it breaks the single responsibility of the method

Another improvement in the implementation is that you don't need to count the spaces. You can walk backward, tracking two positions in parallel:

  • The last position to write to (starts at input.length - 1)
  • The last position in the text (starts at trueLength - 1)

Walk backward as long as the text position is smaller than the end position. If you see a space, overwrite the the values at the position with %20. Otherwise simply copy the input.

void replaceSpaces(char[] input, int trueLength) {
    //int end = input.length - 1;
    int end = trueLength + (countSpaces(input, trueLength) * 2) - 1;
    for (int textEnd = trueLength - 1; textEnd < end; textEnd--) {
        if (input[textEnd] == ' ') {
            input[end--] = '0';
            input[end--] = '2';
            input[end--] = '%';
        } else {
            input[end--] = input[textEnd];
        }
    }
}
\$\endgroup\$
4
  • \$\begingroup\$ Nice, but you are assuming that the input char[] is the exact length required to store the result. The specification suggests it "... has sufficient space ....". You really need to count the spaces first before walking back and replacing them because you need to compute the final length. \$\endgroup\$
    – rolfl
    Mar 5, 2016 at 11:46
  • \$\begingroup\$ Well-spotted, amended my answer \$\endgroup\$
    – janos
    Mar 5, 2016 at 11:55
  • \$\begingroup\$ Wouldn't a for loop be cleaner? for (int textEnd = trueLength - 1; textEnd < end; textEnd-- \$\endgroup\$
    – Caridorc
    Mar 5, 2016 at 12:18
  • 1
    \$\begingroup\$ You're right @Caridorc, amended it \$\endgroup\$
    – janos
    Mar 5, 2016 at 12:37
1
\$\begingroup\$

I feel the solution is quite complicated. Why don't you just shift the array to the right whenever you find a space? Here is my solution in C++.

string urlify(string s, int m) {
    for(int i=0; i<m; ++i) {
        if(s[i] == ' ') {
            shiftRight(s, i+1);
            shiftRight(s, i+2);
            s[i] = '%';
            s[i+1] = '2';
            s[i+2] = '0';
            i+=2;
        }
    }

    return s;
}

Below is the function responsible for shifting (notice that s is passed by reference):

void shiftRight(string &s, int i) {
    int n = s.size();
    char temp1, temp2;

    temp1 = s[i+1];
    s[i+1] = s[i];
    s[i] = ' ';
    for(int j=i+2; j<n; ++j) {
        temp2 = s[j];
        s[j] = temp1;
        temp1 = temp2;
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.