0

the question is about leetcode 344. Reverse String

class Solution {
public:
    string reverseString(string s) {
        char *array = new char[s.length()];
        for(int i=0;i<s.length();i++)
        {    
            array[i] =s[s.length()-i-1];
        }
        string strlist(array);
        printf("%s\n",strlist.c_str());
        return strlist;
    }
};

input is "Sore was I ere I saw Eros." output is ".sorE was I ere I saw eroSnam A\""

it seems that my array has more element than I expected, and I have no idea how to avoid that, anyone can suggest that?

4
  • You forgot to terminate the string with '\0'. Commented May 14, 2018 at 2:04
  • 1
    Why new char[]? Especially when you're already using std::string everywhere? Commented May 14, 2018 at 2:06
  • 2
    Why not simply -- string reverseString(string s) { std::reverse(s.begin(), s.end()); return s; }? Commented May 14, 2018 at 2:08
  • 1
    Don't mix C (e.g. char arrays, naked owning pointers, printf) and C++ (std::string, smart pointers, algorithms, iostream). Commented May 14, 2018 at 2:14

1 Answer 1

4

You forgot to terminate the C-style string with a null character. Also remember to delete[] the allocated array.

string reverseString(string s) {
    char *array = new char[s.length() + 1];
    //                                ^^^
    for(int i=0;i<s.length();i++)
    {    
        array[i] =s[s.length()-i-1];
    }
    array[s.length()] = 0; // Terminate the string
    string strlist(array);
    printf("%s\n",strlist.c_str());
    delete [] array; // Don't forget
    return strlist;
}

There's also some neat ways to do it:

std::string t(s);
std::reverse(t.begin(), t.end());
return t;

Or:

return std::string(s.rbegin(), s.rend());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.