Reverse a String
You are given a string s. You need to reverse the string.
Example 1:
Input:
s = codemummy
Output: ymmumedoc
Example 2:
Input:
s = for
Output: rof
method 1:
reverse by swapping the characters
implementation in c++:
void reverseStr(string& str)
{
int n = str.length();
// Swap character starting from two
// corners
for (int i = 0; i < n / 2; i++)
swap(str[i], str[n - i - 1]);
}
method 2:
Using inbuilt “reverse” function:
implementation in c++:
int main()
{
string str = "geeksforgeeks";
// Reverse str[begin..end]
reverse(str.begin(), str.end());
cout << str;
return 0;
}
method 3:
printing characters from the end one by one till we reach the start
implementation in c++:
int main()
{
string str = "geeksforgeeks";
// Reverse str[begin..end]
reverse(str.begin(), str.end());
cout << str;
return 0;
}
No comments