Time limit exceeded (Java solution)


  • 0
    S

    On using StringBuilder for building the solution, getting Time Limit exceeded for input=20. When using string, getting the Time Limit exceeded at input=14.

    Any pointers as to where I might be going wrong? Or what optimization can be done to it?

    public class Solution {
        public String countAndSay(int n) {
            if(n==0)
                return null;
            String lastPc = new String();
            StringBuilder nextPc = new StringBuilder();
    
            lastPc="1";
            
            if(n==1) return lastPc;
            
            int x,lastX,xCnt;
            
            n--;
            
            while(n>0){
                xCnt=1;
                lastX=Character.getNumericValue(lastPc.charAt(0));
                x=lastX;
                
                for(int i=1;i<lastPc.length();i++){
                    x=Character.getNumericValue(lastPc.charAt(i));
                    if(lastX==x) xCnt++;
                    else {
                        nextPc.append(Integer.toString(xCnt));
                        nextPc.append(Integer.toString(lastX));
                        xCnt=1;
                        lastX=x;
                    }
                }
                
                nextPc.append(Integer.toString(xCnt));
                nextPc.append(Integer.toString(lastX));
                
                lastPc=nextPc.toString();
                n--;
            }
            return nextPc.toString();
        }
    }

Log in to reply
 

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