Problem statement
Write a function that reverses a string. The input string is given as an array of characters s
.
You must do this by modifying the input array in-place with O(1)
extra memory.
Example 1
Input: s = ['h','e','l','l','o']
Output: ['o','l','l','e','h']
Example 2
Input: s = ['H','a','n','n','a','h']
Output: ['h','a','n','n','a','H']
Constraints
1 <= s.length <= 10^5
.s[i]
is a printable ascii character.
Solution: Swap the opposites
Code
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
void reverseString(vector<char>& s) {
int i = 0;
int j = s.size() - 1;
while (i < j) {
swap(s[i++], s[j--]);
}
}
void printResult(vector<char>& s) {
cout << "[";
for (char c : s) {
cout << c << ",";
}
cout << "]\n";
}
int main() {
vector<char> s{'h','e','l','l','o'};
reverseString(s);
printResult(s);
s = {'H','a','n','n','a','h'};
reverseString(s);
printResult(s);
}
Output:
[o,l,l,e,h,]
[h,a,n,n,a,H,]
Complexity
- Runtime:
O(N)
, whereN = s.length
. - Extra space:
O(1)
.