Count and Say
来源:互联网 发布:云打包app平台源码 编辑:程序博客网 时间:2024/05/13 22:52
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.
简单递归,主要读懂题目。
n=1: ans = 1;
n=2: 读n=1的ans,即一个1,ans = 11;
n=3: 读n=2的ans,即两个1,ans = 21;
package leetcode;
public class CountandSay {
public String countAndSay(intn) {
String ans = "1";
int j = 1;
if (n == 1)return "1";
if (n >1){
while (j<n){
ans = revolution(ans);
j++;
}
}
return ans;
}
private String revolution(StringfrontStr) {
// TODO Auto-generated method stub
String ans = "";
int count = 1;
if (frontStr.length() == 1) {
ans =ans + count + frontStr;
returnans;
}
char[] chars = frontStr.toCharArray();
charfrontChar = chars[0];
for (inti = 1; i<chars.length;i++){
if (frontChar ==chars[i]){
count++;
}else{
ans =ans + count + frontChar;
count = 1;
frontChar =chars[i];
}
}
ans =ans + count + frontChar;
returnans;
}
public staticvoid main(String[] args) {
// TODO Auto-generated method stub
System.out.println(new CountandSay().countAndSay(6));
}
}
- LeetCode: Count and Say
- [LeetCode]Count and Say
- LeetCode Count and Say
- [Leetcode] Count and Say
- Count and Say
- Leetcode: Count and Say
- [LeetCode] Count and Say
- LeetCode Count and Say
- Count and Say
- [38]Count and Say
- Count and Say
- Count and Say
- Count and Say
- [LeetCode]Count and Say
- Count and Say
- Count and Say
- [LeetCode] Count and Say
- LeetCode-Count and Say
- 位图的使用
- 细说Angular ng-class
- Android流式布局实现
- 黑马程序员——网络编程总结(一)
- ios swift比较不错的三方库地址
- Count and Say
- 如何在Qt的widget上右键显示菜单
- Android Studio问题集锦
- centos7;windows下安装和使用spice
- mongodb 数据库操作--备份 还原 导出 导入
- Longest Palindromic Substring
- HTTP 响应
- 面向对象程序设计
- 获取手机型号,SDK号,系统版本号