Why leetcode said my output is different with expected output


  • 0
    P

    After I submit my code, I got this error:

    Submission Result: Wrong Answer

    Input: " 1"
    Output: "1"
    Expected: "1"

    clearly I can't tell the difference between Output and Expected. Can anyone help me? thanks.

    Here is my code :

    #include <string> 
    using namespace std;
    
    class Solution {
      public:
    void reverseWords(string &s) {
      size_t n = s.size(); 
      //empty string, return directly 
      if (n==0)
    return; 
    
      int c_begin, c_end, c_ptr, p_ptr=n; //index of starting/ending point for copy/paste 
      char * ss = new char[n+1]; //create another string for saving space, add 1 space for convenience  
    
      //find word and copy in reverse order 
      for(c_begin=0; c_begin<n; c_begin++){
    
    //find starting point 
    while(s[c_begin]==' ' && c_begin<n)
      c_begin++; 
    if (c_begin==n) //no more words to read, stop searching words 
      break; 
    
    //find ending point 
    c_end = c_begin+1;  
    while(s[c_end]!=' ' && c_end<n)
      c_end++; 
    
    //add space for previous word, if p_ptr==n, then no previous word
    if (p_ptr<n) {
      ss[p_ptr] = ' ';
      p_ptr--; 
    }
    
    //copy to string ss 
    for(c_ptr = c_end; c_ptr>c_begin;){
      ss[p_ptr--] = s[--c_ptr]; 
    }
    c_begin = c_end + 1; //since s[c_end] is ' ', we can skip it  
      }
    
      //all characters are spaces, i.e. no word is written to ss
      if (p_ptr==n){
    s.erase(s.begin(), s.end()); //delete all ' 's
    return; 
      }
    
      //copy chars from ss to s
      for (c_ptr=0; p_ptr<(n+1); )
    s[c_ptr++] = ss[++p_ptr]; 
    
      //if c_ptr
      if (c_ptr<n)
    s.erase(c_ptr, n-c_ptr); 
    
      return;
      delete[] ss; 
    }
    

    };


  • 0
    C
    This post is deleted!

  • 0
    S

    English Only.


  • 0
    C
    This post is deleted!

  • 0
    S

    Questions about code you've written must describe the specific problem clearly, elaborate thoughts based on code and preserve code formatting as well. Please read the FAQ for more info.

    Pay attention to "Writing code? Select all code block then click on the {} button to preserve code formatting.” above text editor.


Log in to reply
 

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