题目:
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
代码:
自己的:
class Solution {
public:
string reverseString(string s) {
stack<char> tem;
string result;
for ( auto c : s)
tem.push(c);
while (!tem.empty()){
result += tem.top();
tem.pop();
}
return result;
}
};
别人的:
class Solution {
public:
string reverseString(string s) {
if (s.size() < 2)
return s;
int l = 0, r = static_cast<int>(s.size() - 1);
while (l < r)
{
swap(s[l++], s[r--]);
}
return s;
}
};
别人的效率好。
swap()函数:交换