[JAVA] Why this solution is not efficient enough compare to the others?


  • 0
    S

    '''
    #marked as an inefficient one

    public class Solution {
    public String reverseString(String s) {
    int n = s.length();
    char [] ch1 = s.toCharArray();
    String s1 = "";
    for(int i=0; i<n; i++){
    s1 += Character.toString(ch1[n-1-i]);
    }
    return s1;
    }
    }
    '''

    '''
    #accepted one.
    public class Solution {
    public String reverseString(String s) {
    int n = s.length();
    char [] ch1 = s.toCharArray();
    char [] ch2 = new char[n];
    //String s1 = "";
    for(int i=0; i<n; i++){
    //s1 += Character.toString(ch1[n-1-i]);
    ch2[i] = ch1[n-1-i];
    }
    return new String(ch2);
    }
    }
    '''


  • 0
    2

    would be easier to read with ``` wrapping the code


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.