[LeetCode] 344. Reverse String
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
Given s = "hello", return "olleh".
Thought process:
Use two pointers: one from the start of the string, the other from the end of the string. Swap the characters pointed until they collide.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Solution { public: string reverseString(string s) { int i = 0; int j = s.length() - 1; while (i < j) { swap(s[i], s[j]); i++; j--; } return s; } }; |
Time complexity:
O(n).
Comments
Post a Comment