【LeetCode】Reverse String問題解決レポート

1095 ワード

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
方法1
文字列をビット単位で反転:
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
方法2
文字列に変換すると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