LeetCode – Count and Say (Java)

Problem

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.

Java Solution

The problem can be solved by using a simple iteration. See Java solution below:

public String countAndSay(int n) {
	if (n <= 0)
		return null;
 
	String result = "1";
	int i = 1;
 
	while (i < n) {
		StringBuilder sb = new StringBuilder();
		int count = 1;
		for (int j = 1; j < result.length(); j++) {
			if (result.charAt(j) == result.charAt(j - 1)) {
				count++;
			} else {
				sb.append(count);
				sb.append(result.charAt(j - 1));
				count = 1;
			}
		}
 
		sb.append(count);
		sb.append(result.charAt(result.length() - 1));
		result = sb.toString();
		i++;
	}
 
	return result;
}

6 thoughts on “LeetCode – Count and Say (Java)”

  1. This can be solved in one loop. Check out my Python solution.

    def countAndSay(ml):
    count = 1
    val = ml[0]
    results = ""

    for i in range(1, len(ml)):
    if ml[i] == ml[i-1]:
    count += 1
    else:
    results += f"{count}{val}"
    val = ml[i]
    count = 1
    results += f"{count}{val}"
    return results

  2. Would this be more straightforward?

    static String countAndSay(int n) {

    if(n<0) return "";

    int i = 1;

    String in = String.valueOf(n);

    int cnt = 1;

    StringBuilder builder = new StringBuilder();

    while(i < in.length()) {

    if(in.charAt(i) == in.charAt(i-1)) {

    cnt++;

    } else {

    builder.append(cnt);

    builder.append(in.charAt(i-1));

    cnt = 1;

    }

    i++;

    }

    builder.append(cnt);

    builder.append(in.charAt(i-1));

    return builder.toString();

    }

Leave a Comment