leetcode 38. Count and Say

来源:互联网 发布:24小时制的js时间插件 编辑:程序博客网 时间:2024/06/05 05:55

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.

Subscribe to see which companies asked this question.

这个题真的是表意不明,百度了一下才明白题目讲的是什么意思,就是第一个数是1,n次重组后的字符串是多少,n只和次数有关。

public class Solution {    public String countAndSay(int n) {        String s = "1";        if(n==1){            return "1";        }        for(int i=1;i<n;i++){            StringBuilder tem = new StringBuilder();            int count = 1;            for(int j=0;j<s.length();j++){                if(j>0&&(s.charAt(j)==s.charAt(j-1))){                    count++;                }                else if(j>0){                    tem.append(count);                    tem.append(s.charAt(j-1));                    count = 1;                }            }            tem.append(count);            tem.append(s.charAt(s.length()-1));            s = tem.toString();        }        return s;    }}


原创粉丝点击