Leetcode刷题记——38. Count and Say (计数和说)

来源:互联网 发布:faceyou拍照软件 编辑:程序博客网 时间:2024/06/05 12:00

一、题目叙述:

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,然后第二个数就是用上述方法读第二个数,第三个数就是用上述方法读第二个数。

三、源码:

public class Solution {    public String countAndSay(int n)     {        //String a = "";    if (n == 0) return "";        String b = "1";        for (int j = 1; j < n; j++)        {        String a = "";        int count = 1;        for (int i = 0; i < b.length(); i++)        {        char s = b.charAt(i);        if(i + 1 == b.length())         {        a = a + count + s + "";        }        else if (b.charAt(i + 1) == s)        count ++;                else         {        a = a + count + s + "";        count = 1;        }        }        b = a;        }        return b;    }        public static void main(String[] args)    {    int input = 0;    Solution sol = new Solution();    System.out.println(sol.countAndSay(input));        }}


0 0
原创粉丝点击