Count and Say LeetCode:Mysolution

来源:互联网 发布:数据标注是什么 编辑:程序博客网 时间:2024/06/04 23:37

Count and Say

 Total Accepted: 17238 Total Submissions: 62821My Submissions

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.\

public class Solution {    public String countAndSay(int n) {    if (n <= 0) {    return "";    }    return countSubString(n);    }    String countSubString(int n) {        if (n == 1) {        String s = "1";            return s;        }        String thisN = countSubString(n - 1);        char temp = thisN.charAt(0);        int count = 0;        StringBuffer levelRes = new StringBuffer();        for (int i = 0; i < thisN.length(); i++) {            if (temp == thisN.charAt(i)) {                count++;            } else {                levelRes.append(count);                levelRes.append(temp);                temp = thisN.charAt(i);                count = 1;                            }        }        levelRes.append(count);        levelRes.append(temp);        return levelRes.toString();    }}





0 0