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语言版本:12345678910111213char* 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++版本:12345678910class 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