题目地址:
https://www.lintcode.com/problem/null-terminated-string/description
给定一个C++中的char*格式的字符串,以NULL结尾。要求翻转该字符串。
思路是对撞双指针。先将一个指针移动到字符串NULL的前一位,然后两两做swap即可。代码如下:
class Solution {
public:
/**
* @param str C-String
* @return void
*/
void reverse(char *str) {
// Write your code here
char *l = str, *r = str;
if (r) {
while (*r != NULL) {
r++;
}
}
r--;
while (l < r) {
swap(*l++, *r--);
}
}
};
时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)。