1. Problem Description
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
反转字符串
2. My solution1(另开辟字符串存储)
class Solution {
public:
string reverseString(string s) {
int len=s.length();
string res=s;
for(int i=0;i<len;i++)
res[len-1-i]=s[i];
return res;
}
};
3. My solution2(逐个交换头尾)
class Solution
{
public:
string reverseString(string s)
{
int len=s.length();
int ll=0,rr=len-1;
while(ll<rr)
swap(s[ll++],s[rr--]);
return s;
}
};
4. My solution3 (用栈实现)
顺序压入,逆序弹出。
class Solution
{
public:
string reverseString(string s)
{
stack<char>sta;
int len=s.length();
int i;
for(i=0; i<len; i++)
sta.push(s[i]);
i=0;
while(!sta.empty())
{
char tmp=sta.top();
sta.pop();
s[i++]=tmp;
}
return s;
}
};