Description
Write a function that takes a string as input and returns the string reversed
Thinking Process
- Use two pointers, swap the corresponding characters
Code
public class Solution {
public String reverseString(String s) {
char[] word = s.toCharArray();
int low = 0;
int high = word.length - 1;
while(low < high){
char temp = word[low];
word[low++] = word[high];
word[high--] = temp;
}
return new String(word);
}
}
Complexity
- Time complexity is O(n) as the string is scanned once
- Space complexity is O(n) as there's no way to maniplate strings in place in Java