The count-and-say sequence is the sequence of integers with the first five terms as following:
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 term of the count-and-say sequence.這道題目理解起來有一些晦澀。大意就是對於一串字符串,咱們要用「讀」的方式把這個字符串讀一遍,「讀」結果就是下一個字符串的值。
例如初始字符串是「1」,讀的結果就是1個11,因此第二個字符串就是11。而11讀起來是兩個1,因此第三個字符串就應當是「21」。同理第四個字符串是一個2一個1,所以是"1211"。依次類推
而咱們的目的是,對於輸入的正整數n,咱們要給出第n個字符串是什麼。appExample 1:
Input: 1
Output: "1"
Example 2:
Input: 4
Output: "1211"ui
public class CountandSay_38 { public String countAndSay(int n) { //設置初始字符串 StringBuilder curr = new StringBuilder("1"); StringBuilder prev; for(int i=1;i<n;i++){ prev = curr; //將curr從新賦值 curr = new StringBuilder(); //當前字符 char say = prev.charAt(0); //字符計數 int count = 1; for(int j=1,len=prev.length();j<len;j++){ if(prev.charAt(j) != say){ curr.append(count).append(say); count =1; say = prev.charAt(j); }else{ count++; } } curr.append(count).append(say); } return curr.toString(); } }