Write a function that takes a string as input and returns the string
reversed.

Example 1:

Input: "hello" Output: "olleh" Example 2:

Input: "A man, a plan, a canal: Panama" Output: "amanaP :lanac a ,nalp
a ,nam A"

思路 (BF)

逆序遍历一次stirng, 把遍历到的char都添加到新的string里面. 可以用string.charAt()或者把string转化成array

复杂度

时间O(n) 空间O(n)

代码

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左右

复杂度

时间O(n) 空间O(n)

代码

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);
    }
}

lpy1990
26 声望10 粉丝