LeetCode 344 Reverse String

Posted jessie2009

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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     }

 

 

  

 

  


以上是关于LeetCode 344 Reverse String的主要内容,如果未能解决你的问题,请参考以下文章

leetcode-344. Reverse String

LeetCode_344. Reverse String

Leetcode-344 Reverse String

LeetCode之344. Reverse String

leetcode 344. Reverse String

LeetCode 344 - Reverse String