Write a function that takes a string as input and returns the string
reversed.Example 1:app
Input: "hello" Output: "olleh" Example 2:ui
Input: "A man, a plan, a canal: Panama" Output: "amanaP :lanac a ,nalp
a ,nam A"指針
逆序遍歷一次stirng, 把遍歷到的char都添加到新的string裏面. 能夠用string.charAt()或者把string轉化成arraycode
時間O(n) 空間O(n)input
class Solution { public String reverseString(String s) { if (s.length() <= 1) { return s; } StringBuilder sb = new StringBuilder(); // charAt方法 // for (int i = s.length() -1; i >=0; i--) { // sb.append(s.charAt(i)); // } char[] array = s.toCharArray(); for (int i = array.length -1; i >= 0; i--) { sb.append(array[i]); } return sb.toString(); } }
那string轉換成array, 而後用雙指針方法swich左右string
時間O(n) 空間O(n)it
class Solution { public String reverseString(String s) { if (s.length() <= 1) { return s; } char[] array = s.toCharArray(); int left =0, right = array.length -1; while (left < right) { char tmp = array[left]; array[left] = array[right]; array[right] = tmp; left++; right--; } return new String(array); } }