Time Limit Exceeded?why?


  • 0
    T

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


  • 8
    S

    String is immutable. Hence, every time you are trying to concat , it creates a new object reference. This process is consuming more time in your case. Instead use StringBuilder.

    public String reverseString(String s) {
            int len = s.length();
            if(len ==0 || len==1) return s;
            StringBuffer ret = new StringBuffer(len);
            for(int i=len-1; i>=0;i--){
            	ret.append(s.charAt(i));
            }
            return ret.toString();
        }

  • 0
    S

    +1, this helped me a lot, thanks


Log in to reply
 

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