Reverse String
Problem:
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".
Analysis:
Two pointers, swap left and right.
Solution:
class Solution { public String reverseString(String s) { if (s == null || s.length() == 0) return s; int l = 0, r = s.length() - 1; char[] chars = s.toCharArray(); while(l < r) { char temp = chars[l]; chars[l] = chars[r]; chars[r] = temp; l++; r--; } return new String(chars); } }
评论
发表评论