LeetCode刷题之Count And Say
2018-04-09 本文已影响0人
JRTx
Problem
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, 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"
My Solution
class Solution {
public String countAndSay(int n) {
StringBuilder sb = new StringBuilder();
// 刚开始我的想法是将字符串转换为整数,然后对每一位进行判断,当testcase为11的时候数据太大,没办法通过
/**
if (n == 1) {
sb.append("1");
} else {
long a = Long.parseLong(countAndSay(n - 1));
int[] num = new int[30];
int len = 1;
while (a != 0) {
num[len] = (int)a % 10;
len++;
a = a / 10;
}
int count = 1;
for (int i = len - 1; i > 0; --i) {
if (num[i] == num[i - 1]) {
count++;
} else {
sb.append(count);
sb.append(num[i]);
count = 1;
}
}
}
**/
if (n == 1) {
sb.append("1");
} else {
String str = countAndSay(n - 1) + "*";
char[] x = str.toCharArray();
int count = 1;
for (int i = 0; i < x.length - 1; ++i) {
if (x[i] == x[i + 1]) {
count++;
} else {
sb.append(count);
sb.append(x[i]);
count = 1;
}
}
}
return sb.toString();
}
}
Great Solution
public class Solution {
public String countAndSay(int n) {
StringBuilder curr=new StringBuilder("1");
StringBuilder prev;
int count;
char say;
for (int i=1;i<n;i++){
prev=curr;
curr=new StringBuilder();
count=1;
say=prev.charAt(0);
for (int j=1,len=prev.length();j<len;j++){
if (prev.charAt(j)!=say){
curr.append(count).append(say);
count=1;
say=prev.charAt(j);
}
else count++;
}
curr.append(count).append(say);
}
return curr.toString();
}
}