简体   繁体   中英

Write a program to remove the whitespaces from a given string

I have solved the related question with o(n) time complexity and o(n) space complexity approach as follows; but the interviewed wanted o(n) time complexity with constant space complexity. How can I solve it with constant space complexity?

public static StringBuilder removeWhiteSpaces (String str){

    if (str == null){
        throw new IllegalArgumentException();
    }

    StringBuilder result = new StringBuilder();

    for (int i = 0 ; i < str.length(); i++){
        if (str.charAt(i) != ' '){
        result.append(str.charAt(i));
        }
    }
    return result;  
}

I'm not familiar with Java, but I do remember that String is immutable. What you ask is impossible to do when the string to strip is stored inside String . This is because we can't modify the input, and we need memory to store the result.


However, if you can store the string in mutable memory (eg char[] or StringBuilder ), you can use the following algorithm. Keep two indices, r and w and initialize them to 0. Loop over the string using r , incrementing it for every character you read. Then if that character is not whitespace, write it to w and increment it.

When finished discard the last r - w characters of the string.

Example in C:

void remove_whitespace(char* s) {
    char* r = s;
    char* w = s;

    while (*r) {
        if (!std::isspace(*r)) *w++ = *r;
        ++r;
    }

    *w = 0;
}

There are 2 good ways to improve your answer in Java:

1) There are other whitespace characters besides ' ', and you have to check for them all. Use Character.isWhitespace() or (if you're old like me) <= ' '.

2) You should hold off on making the StringBuilder until you actually see a whitespace character. If you get to the end without one, just return the original string.

Most people in Java would do this with a regex search and replace, but if you have to write a utility function for it, it's better to do it this way (after these improvements), because it will be more efficient.

If the interviewer then asks you for constant space, then the best response is to explain that strings are immutable in Java, so you will have to make an overload of the method that takes a StringBuilder argument that it will then modify. There are ways to do this in other popular languages like C++ and C (orlp's answer), but they are all equivalent to taking a mutable StringBuilder, so there's no need to switch languages.

Was the question in the interview "from a given String" (literally meaning you had to use String str as input), or did you just assume you had to use a String object instead of eg a char[] or StringBuilder .

With String it wouldn't work. As soon as you use something like str.toCharArray() , you would allocate new memory of at least the same length as str . And you can't modify the characters in str , as was already mentioned several times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM