*Count and Say
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.
1 public class Solution { 2 public String countAndSay(int n) 3 { 4 String oldString = "1"; 5 while(--n>0) 6 { 7 StringBuilder sb = new StringBuilder(); 8 char[] oldChar = oldString.toCharArray(); 9 for(int i=0;i<oldChar.length;i++) 10 { 11 int count =1; 12 while((i+1)<oldChar.length&&oldChar[i]==oldChar[i+1]) 13 { 14 count++; 15 i++; 16 } 17 sb.append(String.valueOf(count)+String.valueOf(oldChar[i])); 18 19 } 20 oldString = sb.toString(); 21 22 } 23 24 return oldString; 25 } 26 }