Leetcode: 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.
一次过, 注意29-31行的结尾处理,不要忘记
1 public class Solution { 2 public String countAndSay(int n) { 3 if (n <= 0) return ""; 4 int i = 1; 5 String current = "1"; 6 while (i < n){ 7 current = getnext(current); 8 i++; 9 } 10 return current; 11 } 12 13 public String getnext(String current){ 14 int j = 0, count = 0; 15 char st = current.charAt(0); 16 StringBuffer result = new StringBuffer(); 17 while (j < current.length()){ 18 if (current.charAt(j) == st){ 19 count++; 20 j++; 21 } else{ 22 result.append(count); 23 result.append(st); 24 st = current.charAt(j); 25 count = 1; 26 j++; 27 } 28 } 29 result.append(count); 30 result.append(st); 31 return result.toString(); 32 } 33 }