LeetCode 38. Count and Say(点数)

来源:互联网 发布:工控老鬼如何编程 编辑:程序博客网 时间:2024/05/08 03:32

原题网址:https://leetcode.com/problems/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.


方法:计数实现。

public class Solution {    public String countAndSay(int n) {        List<Integer> nums = new ArrayList<>();        nums.add(1);        for(int i=1; i<n; i++) {            List<Integer> counts = new ArrayList<>();            List<Integer> numbers = new ArrayList<>();            for(int j=0; j<nums.size(); j++) {                if (j == 0 || !numbers.get(numbers.size()-1).equals(nums.get(j))) {                    numbers.add(nums.get(j));                    counts.add(1);                } else {                    counts.set(counts.size()-1, counts.get(counts.size()-1)+1);                }            }            nums = new ArrayList<>();            for(int j=0; j<numbers.size(); j++) {                nums.add(counts.get(j));                nums.add(numbers.get(j));            }        }        StringBuilder sb = new StringBuilder();        for(int i=0; i<nums.size(); i++) sb.append(nums.get(i));        return sb.toString();    }}


0 0
原创粉丝点击