【Leetcode】Count and Say

来源:互联网 发布:手机淘宝怎么认证复核 编辑:程序博客网 时间:2024/06/06 03:32

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.

这道题其实是让数数

111221的下一个数应该是312211

因为111211有3个1,2个2,1个1 和在一起就是312211

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


0 0