Fast java solution. not a hard question but a bit complicated


  • 0
    Y
    public String countAndSay(int n) {
        if(n<2) return ""+n;
        String result = "11";
        for(int i=2;i<n;i++){
            int count=1;
            int length=result.length();
            StringBuffer temp=new StringBuffer();
            for(int j=1;j<length;j++){
                if(result.charAt(j)==result.charAt(j-1))
                    count++;
                else{
                    temp.append(count).append(result.charAt(j-1));
                    count=1;
                }
            }
            temp.append(count).append(result.charAt(length-1));
            result=temp.toString();
        }
        return result;
    }

Log in to reply
 

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