Chinaunix首页 | 论坛 | 博客
  • 博客访问: 255326
  • 博文数量: 170
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1709
  • 用 户 组: 普通用户
  • 注册时间: 2014-05-06 18:01
文章分类

全部博文(170)

文章存档

2016年(11)

2015年(130)

2014年(29)

分类: Java

2015-06-29 19:24:24

注意 char+int 得到的还是int值 直接加到结果字符串上面
可以使用:sBuilder.append(Integer.toString(count)+lastChar);
sBuilder.append(""+count+lastChar);
避免问题
//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 CountandSay {


public static void main(String[] args) {
// TODO 自动生成的方法存根
System.out.print(countAndSay(2));
}
public static String countAndSay(int n) {
String input="1";
for(int i=1;i<n;i++){
input=countAndSayForOneString(input);
}
return input;
}
private  static String countAndSayForOneString(String input) {
// TODO 自动生成的方法存根
char lastChar=input.charAt(0);
int count=1;
StringBuilder sBuilder=new StringBuilder();
for(int i=1;i<input.length();i++){
if(input.charAt(i)==lastChar){
count++;
}else {
sBuilder.append(Integer.toString(count)+lastChar);
count=1;
lastChar=input.charAt(i);
}
}
sBuilder.append(""+count+lastChar);
return sBuilder.toString();
}
}

阅读(731) | 评论(0) | 转发(0) |
0

上一篇:SudokuSolver

下一篇:Combination Sum II

给主人留下些什么吧!~~