Java, with explanation, beat 97%


  • 0
    D
    public class Solution {
        public String countAndSay(int n) 
        {
            StringBuilder str = new StringBuilder("1");
            int id = 1;
            StringBuilder pre = str;
            
            while (id < n)
            {
                str = helper(pre);
                pre = str;
                id++;
            }
            
            return str.toString();
        }
        
        // this method used to get the next string from previous one
        private StringBuilder helper(StringBuilder sb)
        {
            StringBuilder res = new StringBuilder();
            // count, record # of occurence
            int count = 0;
            // content, record char
            char content = 0;
            
            char[] tmp = sb.toString().toCharArray();
            int i = 0;
            while (i < tmp.length)
            {
                if (i == 0) { count = 1; content = tmp[i]; }
                else if (tmp[i] == tmp[i - 1]) { count++; }
                else 
                {
                    // append count and content
                    res.append(count).append(content);
                    count = 1;
                    content = tmp[i];
                }
                i++;
            }
            // final append
            res.append(count).append(content);
            return res;
        }
    }
    

Log in to reply
 

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