38Count and Say

来源:互联网 发布:南京软件谷管委会 编辑:程序博客网 时间:2024/06/06 02:45

/*
 * 题中第1个数为“1”,而不是第0个
 */


public class Solution {

  public String countAndSay(int n) {
if(n<=0) return null;
    List<String> res = new ArrayList<String>();
    res.add("1"); res.add("1"); res.add("11"); res.add("21"); res.add("1211"); res.add("111221");
    if(n<=5) return res.get(n);
    for(int i=6; i<=n; ++i){
    String tmp = res.get(i-1);
    StringBuffer nxt = new StringBuffer();
    int len = tmp.length();
    char v = tmp.charAt(0);
    int c = 1, p = 1;
    while(p < len){
    if(v==tmp.charAt(p)){
    ++c;
    ++p;
    continue;
    }
    nxt.append(c);
    nxt.append(v);
    v = tmp.charAt(p);
    c = 1;
    ++p;
    }
    nxt.append(c);
    nxt.append(v);
    res.add(nxt.toString());
    }
    return res.get(n);
}
}
0 0