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.
n = 1,输出一个1。
n = 2,看n=1那一行,1个1,输出11。
n = 3,看n=2那一行,2个1,输出:21。
n = 4,看n=3那一行,一个2一个1,输出:1211。
以此类推。(注意这里n是从1开始的)
int i--> string : str + ""+i
char c -- > string str + "" + c
int i--> string : str + ""+i
char c -- > string str + "" + c
public class Solution { /** * @param n the nth * @return the nth sequence */ public String countAndSay(int n) { if (n < 0) { return ""; } String cur = "1"; int count = 1; for (int j = 1; j < n; j++) {//因为第0位是1 所以从第一位开始 StringBuilder res = new StringBuilder(); for (int i = 0; i < cur.length(); i++ ) { if (i < cur.length() - 1 && cur.charAt(i) == cur.charAt(i + 1)) { count++; } else { res.append(count + "" + cur.charAt(i)); count = 1; } } cur = res.toString(); } return cur; } }
没有评论:
发表评论