LeetCode:Count and Say

来源:互联网 发布:算法初步高考题含答案 编辑:程序博客网 时间:2024/05/22 13:50


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 "";        if(n == 1) return "1";        StringBuilder ret = new StringBuilder("1");               for(int i = 1;i < n;i++){        StringBuilder s = new StringBuilder();        int len = ret.length();        int j = 0;        while(j < len){        int count = 1;        while((j < len-1)         && (ret.charAt(j) == ret.charAt(j+1))){        count++;        j++;        }        s.append(count+"").append(ret.charAt(j));        j++;        }        ret = s;        }        return ret.toString();    }}

0 0
原创粉丝点击