344.Reverse String

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

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

Java(3ms):

 1 public class Solution {
 2     public String reverseString(String s) {
 3         if (s.length() <= 1){
 4              return s ;
 5          }
 6         char a[] = s.toCharArray() ;
 7         int i  = 0 ;
 8         int j  = s.length() - 1 ;
 9         while(i < j ){
10             char t = a[i] ;
11             a[i] = a[j] ;
12             a[j] = t ;
13             i++ ;
14             j-- ;
15         }
16         return new String(a) ;
17     }
18 }

 

C++(9ms):

 1 class Solution {
 2 public:
 3     string reverseString(string s) {
 4         int i = 0 ;
 5         int j = s.size()-1 ;
 6         while(i < j){
 7             swap(s[i++],s[j--]);
 8         }
 9         return s ;
10     }
11 };

 

 

C++(9ms):

 1 class Solution {
 2 public:
 3     string reverseString(string s) {
 4         if (s == "")
 5           return s ;
 6         if (s.length() == 1)
 7           return s ;
 8         int i = 0 ;
 9         int j = s.length() - 1 ;
10         while(i < j){
11             s[i] = s[i]^s[j] ;
12             s[j] = s[i]^s[j] ;
13             s[i] = s[i]^s[j] ;
14             i++ ;
15             j-- ;
16         }
17         return s ;
18     }
19 };

 

 

C++(9ms):

 1 class Solution {
 2 public:
 3     string reverseString(string s) {
 4         int len = s.length();
 5         string ans = "" ;
 6         for (int i = len - 1 ; i >= 0 ; i--){
 7             ans += s[i] ;
 8         }
 9         return ans ;
10     }
11 };

 

 

C++(12ms):

class Solution {
public:
    string reverseString(string s) {
        reverse(s.begin(),s.end()) ;
        return s ;
    }
};

 

 

C++(26ms):

 1 class Solution {
 2 public:
 3     string reverseString(string s) {
 4         if (s == "")
 5           return s ;
 6         if (s.length() == 1)
 7           return s ;
 8         string leftString = s.substr(0,s.length()/2) ;
 9         string rightString = s.substr(s.length()/2,s.length()) ;
10         return reverseString(rightString) + reverseString(leftString) ;
11     }
12 };

 

C++(9ms):

1 class Solution {
2 public:
3     string reverseString(string s) {
4         return {s.rbegin(),s.rend()};
5     }
6 };

 

posted @ 2016-10-23 20:28  __Meng  阅读(170)  评论(0编辑  收藏  举报