java recursion solution


  • 0
    P
    public class Solution {
        int n;
        String str;
        public String countAndSay(int n) {
            if(n == 1)
            {
                return "1";
            }
            this.n = n;
            helper(2,"11");
            return this.str;
        }
        private void helper(int count,String str)
        {
            if(count == n)
            {
                this.str = str;
                return;
            }
            char[] c = str.toCharArray();
            StringBuilder sb = new StringBuilder();
            int temp = 1;
            for(int i = 0;i<c.length-1;i++)
            {
                if(c[i+1] == c[i])
                {
                    temp++;
                    if(i == c.length-2)
                    {
                        sb.append(temp+"");
                        temp = 1;
                        sb.append(c[i]);
                    }
                }
                else
                {
                    sb.append(temp+"");
                    temp = 1;
                    sb.append(c[i]);
                    if(i == c.length-2)
                    {
                        sb.append(temp+"");
                        temp = 1;
                        sb.append(c[i+1]);
                    }
                }
            }
            helper(++count,sb.toString());
        }
    }
    

Log in to reply
 

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