LeetCode 344. Reverse String

problem:

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

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

first:

class Solution {
    public String reverseString(String s) {
        StringBuilder reversed = new StringBuilder();
        char[] array = s.toCharArray();
        for(int i=array.length-1;0<=i;i--){
            reversed.append(array[i]);
        }
        return reversed.toString();
    }
}

result:

 second try:

换成StringBuffer,效果竟然一样??

3nd:

class Solution {
    public String reverseString(String s) {
        
        char[] array = s.toCharArray();
        char[] reversed = new char[array.length];
        for(int i=array.length-1;0<=i;i--){
            reversed[array.length-1-i]=array[i];
        }
        return new String(reversed);
    }
}

result:

可见,用数组代替string和StringBuffer或StringBuilder会更快。

conclusion:

https://stackoverflow.com/questions/355089/difference-between-stringbuilder-and-stringbuffer

根据上述链接, StringBuilder因为没有同步,会比StringBuffer更快。但为什么在leetCode上两者速度一样?莫非LeetCode做了默认优化?

猜你喜欢

转载自www.cnblogs.com/hzg1981/p/8946776.html