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;
}
Category >> Algorithms >> Interview >> Java  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • funcprogrammer

    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();

    }