码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 344 Reverse String

时间:2018-09-30 14:43:01      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:out   rar   null   stringbu   sed   hello   ack   result   oid   

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

标签:out   rar   null   stringbu   sed   hello   ack   result   oid   

原文地址:https://www.cnblogs.com/jessie2009/p/9729118.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!