【LeetCode】 38. Count and Say 外观数列(Easy)(JAVA)

【LeetCode】 38. Count and Say 外观数列(Easy)(JAVA)

题目地址: https://leetcode.com/problems/count-and-say/

题目描述:

The count-and-say sequence is the sequence of integers with the first five terms as following:

1.     1
2.     11
3.     21
4.     1211
5.     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 where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. You can do so recursively, in other words from the previous member read off the digits, counting the number of digits in groups of the same digit.

Note: Each term of the sequence of integers will be represented as a string.

Example 1:

Input: 1
Output: "1"
Explanation: This is the base case.

Example 2:

Input: 4
Output: "1211"
Explanation: For n = 3 the term was "21" in which we have two groups "2" and "1", "2" can be read as "12" which means frequency = 1 and value = 2, the same way "1" is read as "11", so the answer is the concatenation of "12" and "11" which is "1211".

题目大意

「外观数列」是一个整数序列,从数字 1 开始,序列中的每一项都是对前一项的描述。前五项如下:

1.     1
2.     11
3.     21
4.     1211
5.     111221

1 被读作 “one 1” (“一个一”) , 即 11。
11 被读作 “two 1s” (“两个一”), 即 21。
21 被读作 “one 2”, “one 1” (“一个二” , “一个一”) , 即 1211。

给定一个正整数 n(1 ≤ n ≤ 30),输出外观数列的第 n 项。

注意:整数序列中的每一项将表示为一个字符串。

解题方法

遍历,判断相同字母个数

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

执行用时 : 3 ms, 在所有 Java 提交中击败了 66.24% 的用户
内存消耗 : 36.8 MB, 在所有 Java 提交中击败了 5.10% 的用户

发布了81 篇原创文章 · 获赞 6 · 访问量 2306

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/104668945