Write a function that reverses a string. The input string is given as an array of characters s.
You must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Input: s = ["h","e","l","l","o"] Output: ["o","l","l","e","h"]
Example 2:
Input: s = ["H","a","n","n","a","h"] Output: ["h","a","n","n","a","H"]
class Solution {
public:
void reverseString(vector<char>& s) {
char ch;
int len = s.size();
for(int i = 0; i<len/2 ; i++){
ch = s[i];
s[i] = s[len-i-1];
s[len-i-1] = ch;
}
}
};
该博客介绍了一个C++实现的字符串反转函数,通过交换字符串首尾元素来达到反转效果。函数接收一个字符数组作为输入,并在原地修改数组实现反转,确保额外空间复杂度为O(1)。示例展示了如何反转包含英文字符和大小写字母的字符串。

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



