LeetCode 344: Reverse String

Write a function that takes a string as input and returns the string reversed. Example: Given s = "hello", return "olleh".

代码

C语言版本:

1
2
3
4
5
6
7
8
9
10
11
12
13
char* reverseString(char* s) {
int left = 0;
int right = strlen(s) - 1;
while (left<right){
s[left] ^= s[right];
s[right] ^= s[left];
s[left] ^= s[right];
left++;
right--;
}
return s;
}

476 / 476 test cases passed.
Status: Accepted
Runtime: 4 ms
C++版本:

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
string reverseString(string s) {
int l = 0, r = s.size() - 1;
while (l < r){
swap(s[l++], s[r--]);
}
return s;
}
};

476 / 476 test cases passed.
Status: Accepted
Runtime: 12 ms

分享到 评论