I can't see a way to do it in less than O(n). I got time limit exceeded, Can any one point at what am i doing worng?

  • -2

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

  • 4

    In Java, String is immutable, that means every time you use "+=", it will construct a new string.
    That is the reason while it is not linear any more. It will become O(n^2).

  • 0

    I think that i had reduced to n/2,but just so, i still after 80% personal.
    char* reverseString(char* s) {
    int i = 0;
    int len = strlen( s );
    if( len <2 )
    return s;

        char * temp= s+len-1;
        char ctemp;
        while( temp > s )
                ctemp = *temp;
                *temp-- = *s;
                *s++ = ctemp;
        return s-(len/2);


Log in to reply

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