您的位置:首页 > 其它

344. Reverse String

2016-05-13 11:12 337 查看

344. Reverse String

Description:

Write a function that takes a string as input and returns the string reversed.

Example:

Given s = “hello”, return “olleh”.

Link:

https://leetcode.com/problems/reverse-string/

Analysis:

这种问题第一反应就是使用递归来解决,这里我使用stack来实现的。

Source Code(C++):

#include <iostream>
#include <string>
#include <stack>
using namespace std;

class Solution {
public:
string reverseString(string s) {
stack<char> a;
for(int i=0; i<s.length(); i++) {
a.push(s.at(i));
}
string s_reverse;
while(!a.empty()) {
s_reverse += a.top();
a.pop();

}
return s_reverse;
}
};

int main()
{
Solution a;
string str = "hello";
cout << a.reverseString(str);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: