Leetcode: Reverse String

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

Example:
Given s = "hello", return "olleh".

After the API changes

 1 class Solution {
 2     public void reverseString(char[] s) {
 3         if (s == null || s.length == 0) return;
 4         int l = 0, r = s.length - 1;
 5         while (l < r) {
 6             char temp = s[l];
 7             s[l] = s[r];
 8             s[r] = temp;
 9             l ++;
10             r --;
11         }
12     }
13 }

注意没有append(0, s.charAt(i)), 是sb.insert(0, charAt(i));

 1 public class Solution {
 2     public String reverseString(String s) {
 3         if (s == null) return null;
 4         StringBuffer sb = new StringBuffer();
 5         for (int i=s.length()-1; i>=0; i--) {
 6             sb.append(s.charAt(i));
 7         }
 8         return sb.toString();
 9     }
10 }
1 public class Solution {
2     public String reverseString(String s) {
3         return new StringBuffer(s).reverse().toString();
4     }
5 }
原文地址:https://www.cnblogs.com/EdwardLiu/p/6093168.html