344-reverse-string
Question
https://leetcode.com/problems/reverse-string/description/
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
Thought Process
- Two Pointers
- Use two pointer to track the start and end of string
- Swap the character at each pointer and then shrink toward the center
- Time complexity O(n)
- Space complexity O(1)
Solution
class Solution {
public String reverseString(String s) {
char[] chars = s.toCharArray();
int i = 0, j = chars.length - 1;
while (i < j) swap(chars, i++, j--);
return String.valueOf(chars);
}
private void swap(char[] chars, int i, int j) {
char tmp = chars[i];
chars[i] = chars[j];
chars[j] = tmp;
}
}