Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
这个题目比较straightforward,因为我们可以从这个string的首尾开始swap,直到相遇
class Solution {
public:
string reverseString(string s) {
if (s.size() <= 1) {
return s;
}
for (int i=0, j=s.size()-1; i<j; ++i, --j) {
char temp = s[i];
s[i] = s[j];
s[j] = temp;
}
return s;
}
};
本文介绍了一个简单的C++函数,该函数接收一个字符串作为输入并返回其反转后的字符串。通过交换字符串首尾字符的方式实现,直至中间位置。例如输入hello,则返回olleh。
248

被折叠的 条评论
为什么被折叠?



