leetcode344. Reverse String
题目
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = “hello”, return “olleh”.
翻译成中文就是反转一个字符串,给的例子很好理解。
解题思路
这道题很简单,关键是时间复杂度和空间复杂度的问题。看到的第一眼很容易想到再申请一个string变量,从尾向头扫描输入的字符串,并赋给新的string变量。但这样还是需要一定的空间复杂度。
稍微思考一下,空间复杂度可以为O(1)。即一个指向头,一个指向尾,不停交换即可。
PS:用到了几个函数
1. string里面的size()用于获取字符串字节数(带字符串尾‘\0’的长度)
2. swap()函数,用于交换两个变量的值
AC代码
class Solution {
public:
string reverseString(string s) {
int i=0;
int j=s.size()-1;
for(i,j;j>i;i++,j--){
swap(s[i],s[j]);
}
return s;
}
};
AC时间为9ms,暂时没有更好的优化想法。
总结
本题难度为easy,本身很简单,没啥说的。