String
Description:
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 12. 113. 214. 12115. 111221
1
is read off as"one 1"
or11
.11
is read off as"two 1s"
or21
.21
is read off as"one 2
, thenone 1"
or1211
.Given an integer n, generate the nth term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1Output: "1"Example 2:
Input: 4Output: "1211"
个人觉得这个题意实在是反人类!!!
在此说明一下题意:
例如,5对应111221,6的结果就是对应读5得到的,也就是3个1、2个2、1个1,即:312211
my Solution:
public class Solution { public String countAndSay(int n) { StringBuffer sb = new StringBuffer("1"); for (int i = 1; i < n; i++) { StringBuffer next = new StringBuffer(); int count = 1; for (int j = 0; j < sb.length(); j++) { if (j+1 < sb.length() && sb.charAt(j) == sb.charAt(j+1)) { count++; } else { next.append(count).append(sb.charAt(j)); count = 1; } } sb = next; } return sb.toString(); }}