【LeetCode算法-38】Count and Say
2023-09-14 08:59:10 时间
LeetCode第38题
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.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1
Output: "1"
Example 2:
Input: 4
Output: "1211"
翻译:
简单来说就是:
第一次:1
第二次:一个1:11
第三次:两个1:21
第四次:一个2,一个1:1211
第五次:一个1,一个2,两个1:111221
第六次:三个1,两个2,一个1:312211
以此类推...
思路:
首先想想每一次的比较,肯定是首先固定一个数值,然后循环遍历与其相比较
for(int i = 1;i<value.length();i++){
if(temp == value.charAt(i)){
count++;
}else{
//第一次出现不相等
result.append(count).append(temp);
count = 1;
temp = value.charAt(i);
}
}
else方法块里的就是关键:一旦出现不相等的情况,就append前面的结果,然后更新那个固定值,接着继续遍历比较
最外面的话很明显就是采用递归了,从1开始,一轮一轮的计算上去,直到想要的结果
String result = "1";
while(--n>0){
result = getOnce(result);
System.out.println(result);
}
完整代码如下
class Solution {
public String countAndSay(int n) {
String result = "1";
while(--n>0){
result = getOnce(result);
System.out.println(result);
}
return result;
}
public String getOnce(String value){
StringBuffer result = new StringBuffer();
char temp = value.charAt(0);
int count = 1;
for(int i = 1;i<value.length();i++){
if(temp == value.charAt(i)){
count++;
}else{
//第一次出现不相等
result.append(count).append(temp);
count = 1;
temp = value.charAt(i);
}
}
return result.append(count).append(temp).toString();
}
}
每次递归打印的结果就是:
11
21
1211
111221
312211
...
欢迎关注我的微信公众号:安卓圈
相关文章
- Java实现 LeetCode 740 删除与获得点数(递推 || 动态规划?打家劫舍Ⅳ)
- Java实现 LeetCode 334 递增的三元子序列
- Java实现LeetCode 111. Minimum Depth of Binary Tree
- Java实现 LeetCode 212 单词搜索 II
- 【LeetCode算法-27】Remove Element
- 【LeetCode算法-20】Valid Parentheses
- 【LeetCode算法-9】Palindrome Number
- 【刷题】【LeetCode】000-十大经典排序算法
- 【LeetCode算法-38】Count and Say
- 【LeetCode算法-21】Merge Two Sorted Lists
- 【LeetCode算法-13】Roman to Integer
- leetcode算法第9题
- leetcode算法第三题
- 【LeetCode 简单 矩阵】14 最长公共前缀
- Leetcode 1984. 学生分数的最小差值(可以,已解决)
- LeetCode Implement strStr()(Sunday算法)
- LeetCode 74:Search a 2D Matrix
- 【Leetcode刷题Python】LeetCode 478. 在圆内随机生成点
- 【Leetcode刷题Python】174. 地下城游戏
- 【LeetCode】21. 合并两个有序链表
- 【LeetCode】13.罗马数字转整数
- LeetCode刷题训练 && LeetCode算法和数据结构学习(一)