Leetcode38 Count and Say

来源:互联网 发布:2345网络电视直播 编辑:程序博客网 时间:2024/06/09 23:06

Count and Say

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.

Solution

  • 没什么算法上的难度,具体就是数每一个数都有多少个。
public class Solution {    public String countAndSay(int n) {        if(n<1) return "";        StringBuffer sb = new StringBuffer();        StringBuffer temp = new StringBuffer();        sb.append(1);        for(int i=1;i<n;i++){            for(int j=0;j<sb.length();){                char c = sb.charAt(j);                int len = 0;                while(j<sb.length()&&sb.charAt(j)==c){                    len++;                    j++;                }                temp.append(len);                temp.append(c);            }            sb = temp;            temp = new StringBuffer();        }        return sb.toString();            }}
0 0
原创粉丝点击