Skip to content

Latest commit

 

History

History
48 lines (39 loc) · 865 Bytes

38. Count and Say.md

File metadata and controls

48 lines (39 loc) · 865 Bytes

38. Count and Say

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.

tag:

  • string

Solution

java

	public String countAndSay(int n) {
		if (n <= 0)
			return "";
		String pre = "1";
		for (int i = 2; i <= n; i++) {
			StringBuffer next = new StringBuffer();
			int count = 1;
			for (int j = 1; j < pre.length(); j++) {
				if (pre.charAt(j) == pre.charAt(j - 1))
					count++;
				else {
					next.append(count);
					next.append(pre.charAt(j - 1));
					count = 1;
				}
			}
			next.append(count);
			next.append(pre.charAt(pre.length() - 1));
			pre = next.toString();
		}
		return pre;
	}

go