【LeetCode】Reverse String 解题报告

Reverse String

[LeetCode]

https://leetcode.com/problems/reverse-string/

Total Accepted: 11014 Total Submissions: 18864 Difficulty: Easy

Question

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

Example:

Given s = “hello”, return “olleh”.

Ways

方法一

字符串按位翻转:

public class Solution {
    public String reverseString(String s) {
        StringBuffer answer=new StringBuffer("");
        int tail=s.length()-1;
        for(int i=tail;i>=0;i--){
            answer.append(s.charAt(i));
        }
        return answer.toString();

    }
}

AC:6ms

方法二

转换为字符串后,in-place翻转

public class Solution {
    public String reverseString(String s) {
        char[] chars=s.toCharArray();
        for(int i=0;i<chars.length/2;i++){
            char temp=chars[i];
            chars[i]=chars[chars.length-1-i];
            chars[chars.length-1-i]=temp;
        }
        return new String(chars);

    }
}

AC:3ms

Date

2016/4/29 21:27:57

你可能感兴趣的:(LeetCode)