Failing testcase for input string = " ". Replacing string in place in C.


  • 0
    A
    • Reverse the string and then reverse each word. To accomplish this i have a function 'reverseStrings' which simply reverses strings in place. From the main function I invoke this function for the entire string and then each word.
    • My code fails the testcase where input = " ". Obviously, the expected output should also be " ". But the testcase expects "" to be returned.
    • if anyone else has faced this problem, please let me know. Also did you handle this case explicitly ?
    void reverseStrings(char *s,  int length) {
        int i;
        for(i=0; i<length/2; i++){
            char ch = s[i];
            s[i] = s[length-1-i];
            s[length-1-i] = ch;
        }
    }
    
    void reverseWords(char *s) {
        if(s == NULL || strcmp(s, " ") == 0){
            return;
        }
    
        int len =  strlen(s);
    
        reverseStrings(s, len);
        int j;
        int start_index = 0;
        for(j = 0; j<len; j++){
            if(s[j] == ' '){
                reverseStrings(s+start_index, j-start_index);
                start_index = j+1;
            }
        }
        reverseStrings(s+start_index, j-start_index);
    }
    

  • 0
    T

    The expected output is correct. As the clarification says:

    Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.