原题网址: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();
}
}

本文介绍了一种生成计数并说序列的方法,通过迭代计算实现了给定整数n时生成对应的序列。文章提供了一个Java实现示例,详细展示了如何通过计数实现的方式构建这一特殊数列。
1137

被折叠的 条评论
为什么被折叠?



