leetcode 344. Reverse String


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

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

第一次使用的是string来做,从后往前遍历输入的string,依次存入新的string中,提交的时候没有通过,因为超时了。超时的方法如下:

public class Solution {
    public String reverseString(String s) {
        String result = "";
        for(int i=s.length()-1;i>=0;i--){
            result += s.charAt(i);
        }
        return result;
    }
}

第二次把string换成了StringBuilder,问题解决了。

public class Solution {
    public String reverseString(String s) {
        if(s == "" || s.length() == 0) return "";
        
        StringBuilder sb = new StringBuilder();
        for(int i = s.length() -1;i>=0;i--){
            sb.append(s.charAt(i));
        }
        
        return sb.substring(0, sb.length());
    }
   
}
原文地址:https://www.cnblogs.com/iwangzheng/p/5706969.html