Woodstock Blog

a tech blog for general algorithmic interview questions

[LeetCode 38] Count and Say

Question

link

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.

Stats

Frequency 2
Difficulty 2
Adjusted Difficulty 1
Time to use ----------

Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red)

Solution

This is a implementation question, not difficult.

My code

code 1

public class Solution {
    public String countAndSay(int n) {
        String num = "1";
        for (int i = 1; i < n; i++) {
            num = say(num);
        }
        return num;
    }

    private String say(String input) {
        // 21 -> 1211
        int len = input.length();
        String output = "";
        int left = 0;
        int right = 0;
        while (right < len) {
            left = right;
            // forward right until right pointer to a different value
            // compared to that pointed by left pointer
            while (right < len && input.charAt(left) == input.charAt(right)) {
                right++;
            }
            output += String.valueOf(right - left);
            output += input.charAt(left);
        }
        return output;
    }
}

code 2

public String countAndSay(int n) {
    String s = "1";
    for (int i = 2; i <= n; i ++) {
        char[] nums = s.toCharArray();
        String newS = "";
        int len = nums.length, left = 0, right = 0;
        while (right < len) {
            while (right < len && nums[left] == nums[right]) right ++;
            newS += (right - left) + "" + nums[left];
            left = right;
        }
        s = newS;
    }
    return s;
}