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.
http://oj.leetcode.com/problems/count-and-say/
public class Solution { public String countAndSay(int n) { if(n==1){ return "1"; } String sr = "1"; for(int i=1;i<n;i++){ char[] ch= sr.toCharArray(); char cha=ch[0]; int count=1; StringBuilder sb = new StringBuilder(); for(int j=1;j<ch.length;j++){ if(ch[j]==cha){ count++; }else{ sb.append(String.valueOf(count)); sb.append(cha); cha = ch[j]; count=1; } } sb.append(String.valueOf(count)); sb.append(cha); sr = sb.toString(); } return sr; } }
原文:http://www.cnblogs.com/yixianyixian/p/3690307.html