Wednesday, January 7, 2015

LeetCode 38: Count and Say

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.

Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
public class Solution {
    public String countAndSay(int n) {
        // Return nth number
        // 1 - one one
        // 11 - two one
        // 21 - one two one one
        // 1211 - one one one two two one
        if (n <= 0)
            return "";
            
        String result = "1";
            
        for (int i = 1; i < n; i++)
            result = gen(result);
            
        return result;
    }
    
    private String gen(String s)
    {
        String ret = "";
        int m = s.length();
        int i=0, j;
        
        while (i < m)
        {
            j = i+1;
            
            while (j < m)
            {
                if (s.charAt(j) == s.charAt(i))
                    j++;
                else
                    break;
            }
            
            ret += String.valueOf(j-i); // (j-i) --- Number of the same digit
            ret += s.charAt(i);
            
            i = j;
        }
        
        return ret;
    }
}

No comments:

Post a Comment