题目:
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) {
if (s.length() <= 1) {
return s;
}
for (int i = 0; i < s.length() / 2; ++i) {
swap(s[i], s[s.length() - 1 - i]);
}
return s;
}
};
本文介绍了一个简单的C++函数,该函数接收一个字符串作为输入,并返回其反转后的字符串。通过交换字符串首尾字符的方式实现,适用于初学者理解递归与迭代的概念。
369

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



