Write a method that reverses the given input string. Example: Given s = “12345”, return “54321”.
STL
The C++ STL provides the reverse method that does the job.
class Solution {
public:
string reverseString(string s) {
reverse(s.begin(), s.end());
return s;
}
};
The string constructor takes the iterator so we can use rbegin() and rend() in which the ‘r’ means reversed.
class Solution {
public:
string reverseString(string s) {
auto x = string(s.rbegin(), s.rend());
return x;
}
};
Two Pointers
We initialize two pointers, from the start and end respectively. Swap two characters until these pointers meet in the middle. O(n) complexity.
class Solution {
public:
string reverseString(string s) {
int i = 0, j = s.length() - 1;
while (i < j) {
swap(s[i++], s[j--]);
}
return s;
}
};
Make a Copy
If we make a copy, we can re-assign the reverse characters easily. O(n) complexity.
class Solution {
public:
string reverseString(string s) {
string x = s;
for (int i = 0; i < s.length(); i ++) {
x[i] = s[s.length() - i - 1];
}
return x;
}
};
Add Character Reverse
Another way is to add character in the reverse order.
class Solution {
public:
string reverseString(string s) {
string x = "";
for (int i = 0; i < s.length(); i ++) {
x = s[i] + x;
}
return x;
}
};
See also: Reverse a Sentence (Sentence Reversal Algorithm)
–EOF (The Ultimate Computing & Technology Blog) —
Last Post: Last Minute Tips before Phone Interview
Next Post: Dynamic Programming - Integer Break