您的位置:首页 > 其它

344. Reverse String

2017-02-28 22:24 204 查看

题目

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

Example:

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

Subscribe to see which companies asked this question.

思路

比较简单,两个index往中间靠,并互换字符

代码

class Solution {
public:
void swapChar(string &s,size_t beginIndex,size_t endIndex)
{
char tempChar = s[beginIndex];
s[beginIndex] = s[endIndex];
s[endIndex] = tempChar;
}

string reverseString(string s) {
size_t length = s.size();
if(length <= 1)
{
return s;
}

for(size_t i=0;i< length/2;i++)
{
swapChar(s,i,length-1-i);
}
return s;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: