C++ code for Reverse String

  • 0

    For reversing the string, we can declare a new string and then copy character by character from the end.
    Code for the same is:

    class Solution {
    string reverseString(string s) {
    string s1 ="";
    for(int i=s.length()-1;i>=0;i--)
    return s1;

  • 0

    You can also simply reverse the string in place without having to create a new string object by using std::reverse on the input string s like this:

    #include <algorithm> // std::reverse
    // ...
    std::reverse(begin(s), end(s));
    // or you can use a for loop to swap 2 opposite characters of s like this:
    const size_t s_len{s.length()};
    for (size_t i{}; i < s_len / 2; i++) swap(s[i], s[s_len - 1 - i]);

Log in to reply

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