leetcode解题方案--038--count and say

来源:互联网 发布:java写的桌面程序 编辑:程序博客网 时间:2024/05/22 12:03

题目

The count-and-say sequence is the sequence of integers with the first five terms as following:

  1. 1
  2. 11
  3. 21
  4. 1211
  5. 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.

后一个字符串是前一个字符串的读法

public static String countAndSay(int n) {        if (n<1) {            return "";        }        if (n==1) {            return "1";        }else {            char[] str = countAndSay(n-1).toCharArray();            int count = 1;            char curr = ' ';            StringBuffer xx = new StringBuffer("");            for (int i = 0;i<str.length;i++) {                if (str[i]!=curr) {                    if (curr!=' ') {                        xx.append(count);                        xx.append(curr);                    }                    count = 1;                    curr = str[i];                } else {                    count++;                }            }            xx.append(count);            xx.append(curr);            return xx.toString();        }    }
原创粉丝点击