Saturday, August 20, 2016

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.
Solution:
  • An iterative solution is intuitive
  • Since we have to generate the n-th sequence for an integer, it is useful to write a helper that takes a String and generates it's count - and - say sequence
  • Initialize starting sequence to "1"
  • To generate the n-th sequence for a number n, call the helper n - 1 times and keep updating the sequence
public class Solution {
    public String countAndSay(int n) {
        String curSeq = "1";
        
        for (int p = 2; p <= n; p++) {
            curSeq = countAndSayIt(curSeq);
        }
        return curSeq;
    }
    
    private String countAndSayIt(String curSeq) {
        int pos = 0;
        int N = curSeq.length();
        String countAndSaySeq = "";
        
        while (pos < N) {
            char c = curSeq.charAt(pos);
            int freq = 1;
            pos++;
            
            // check if c repeats consecutively and update freq
            while (pos < N && curSeq.charAt(pos) == c) {
                freq++;
                pos++;
            }
            
            countAndSaySeq += (freq + "" + c);
        }
        
        return countAndSaySeq;
    }
}

No comments:

Post a Comment