题目描述

写出一个程序,接受一个字符串,然后输出该字符串反转后的字符串。(字符串长度不超过1000)

 

示例

输入

"abcd"

返回值

"dcba"

 

public class ReverseStrMe {
    public static void main(String[] args) {
        ReverseStrMe reverseStrMe = new ReverseStrMe();
        System.out.println(reverseStrMe.solve3("abcdef"));
    }

    /*
     使用charAt方法
     */
    public String solve1 (String str) {
        if(null == str || str.length() <= 1){
            return str;
        }

        StringBuilder stringBuilder = new StringBuilder();
        for (int i = str.length()-1; i>=0; i--) {
            stringBuilder.append(str.charAt(i));
        }

        return stringBuilder.toString();
    }

    /*
     使用toCharArray方法
     */
    public String solve2 (String str) {
       if(null == str || str.length() <= 1){
           return str;
       }

        int head = 0;
        int end = str.length()-1;

        char temp = '0';
        char[] charArr = str.toCharArray();

        while(head < end){
            temp = charArr[head];
            charArr[head] = charArr[end];
            charArr[end] = temp;
            head++;
            end--;
        }

       return String.valueOf(charArr);
    }

    /*
    使用StringBuilder的reverse()方法
    */
    public String solve3 (String str) {
        if(null == str || str.length() <= 1){
            return str;
        }
        
        StringBuilder stringBuilder = new StringBuilder(str);

        stringBuilder.reverse();

        return stringBuilder.toString();
    }

}