Question:
Reverse a String with C++

Summary

The the below code we defines a class Solution with a method reverseWord that takes a string str as input and reverses its characters in place. 


The function uses a two-pointer approach, starting from the beginning (s) and end (e) of the string, swapping characters iteratively until the pointers meet in the middle.


Solution:

//User function Template for C++

class Solution

{

    public:

    string reverseWord(string str)

    {

        // Your code goes here

        int s=0;

        int e=str.size()-1;

        while(s<e){

            swap(str[s++],str[e--]);

        }

        return str;

        

        

    }

};


Explanation:

  • The function reverseWord reverses the characters of the input string str in place.

  • Two pointers (s and e) are initialized at the beginning and end of the string, respectively.

  • The while loop continues until the start pointer (s) is less than the end pointer (e).

  • Inside the loop, characters at the start and end positions are swapped using swap.

  • Both pointers are incremented and decremented, moving towards the center of the string.

  • The reversed string is then returned.


Suggested blogs:

>What is meant by progressive framework?

>Why logged user object is all strings in Vuejs and Laravel 10?

>How to get the date and time and display it in a defineProps in Vuejs?

>Fix error while retrieving pages from a pdf using convert_from_path (pdf2image)

>How .transform handle the splitted groups?

>Can I use VS Code's launch config to run a specific python file?

>Python: How to implement plain text to HTML converter?

>How to write specific dictionary list for each cycle of loop?

>Reading a shapefile from Azure Blob Storage and Azure Databricks


Ritu Singh

Ritu Singh

Submit
0 Answers