LeetCode 344 Reverse String

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"
 1 //方法一:用StringBuilder, Time: O(n), Space: O(n)
 2 public String reverseString(String s) {
 3         if (s == null || s.length() == 0) {
 4             return s;
 5         }
 6         
 7         StringBuilder sb = new StringBuilder();
 8         
 9         for(int i = s.length() - 1; i >= 0; i--) {
10             sb.append(s.charAt(i));
11         }
12         
13         return sb.toString();
14     }
15 
16 
17 //方法二:用array, Time: O(n), Space: O(n)
18 public String reverseString(String s) {
19         if (s == null || s.length() == 0) {
20             return s;
21         }
22         
23         char[] result = s.toCharArray();
24         int i = 0;
25         int j = result.length - 1;
26         
27         while (i < j) {
28             swap(i, j, result);
29             i++;
30             j--;
31         }
32         
33         return new String(result);//最后要把array再转回string
34     }
35     
36     public void swap(int i, int j, char[] c) {
37         char temp = c[i];
38         c[i] = c[j];
39         c[j] = temp;
40     }

 

 

  

 

  

posted @ 2018-09-30 13:00  一丝清风一抹红尘  阅读(104)  评论(0编辑  收藏  举报