您的位置:首页 > 其它

LeetCode(51)- Count and Say

2016-04-12 16:57 225 查看

题目:

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.


思路

题意:给定一个整数字符串,下一个是对上一个的描述,比如”11122211“,下一个是3个1,3个2,2个1,是”313221“,给定n,求出第n个整数字符串

关键在于找到当前和前一个的关系,比较一个整数字符串的元素,紧邻是否相同,用变量num统计连续相同的个数,当不想同时候,stringBuffer.append(num).append(元素),num= 1;相同时,num++;

-

代码:

public class Solution {
public String countAndSay(int n) {
String str = "1";
for(int i = 1;i < n;i++){
int num = 1;
StringBuffer sb = new StringBuffer();
for(int j = 1;j < str.length();j++){
if(str.charAt(j) == str.charAt(j-1)){
num++;
}else{
sb.append(num).append(str.charAt(j-1));
num = 1;
}
}
sb.append(num).append(str.charAt(str.length()-1));
str = sb.toString();
}
return str;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: