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:

Change to StringBuffer, the effect is the same? ?

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:

It can be seen that replacing string and StringBuffer or StringBuilder with an array will be faster.

conclusion:

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

According to the above link, StringBuilder will be faster than StringBuffer because there is no synchronization. But why are both the same speed on leetCode? Could it be that LeetCode has done a default optimization?

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324856337&siteId=291194637