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.
注意最后的一个count不能忘记
Java code:
public String countAndSay(int n) { String s = "1"; int i = 1; while(i < n){ int j = 0; char a = s.charAt(0); int count = 0; String nexts = ""; while(j < s.length()){ if(s.charAt(j) == a){ count++; j++; }else{ nexts += count + String.valueOf(a); a = s.charAt(j); count = 0; } } nexts += count + String.valueOf(a);//the last part s = nexts; i++; } return s; }
No comments:
Post a Comment