Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "oleo".
Solution
Idea: swap characters
<span style="font-size:14px;">class Solution {
public:
string reverseString(string s) {
for(int i=0; i<floor(s.size()/2); i++){
int j = s.size() - i - 1;
char ctemp = s[j];
s[j] = s[i];
s[i] = ctemp;
}
return s;
}
};</span>
Solution
Idea: rearrange string by inverse order
<span style="font-size:14px;">class Solution {
public:
string reverseString(string s) {
int len = s.length();
string ss = "";
for (int i=0; i<len; i++)
ss += s[len-i-1];
return ss;
}
};</span>