Leetcode:38. Count and Say(JAVA)
2016-03-15 19:49
519 查看
【问题描述】
The count-and-say sequence is the sequence of integers beginning as follows:
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
【思路】
没有使用什么技巧,两层循环,1到n循环,内层依次扫描上一层数字。
【code】
public class Solution {
public String countAndSay(int n) {
if (n < 0) {
return null;
}
String result = "1";
StringBuffer sb = null;
if (n == 1) {
return result;
} else {
for (int i = 2; i <= n; i++) {
sb = new StringBuffer();
int count = 0;
char c = result.charAt(0);
for (int j = 0; j < result.length(); j++) {
if (result.charAt(j) == c) {
count++;
} else {
sb.append(count);
sb.append(c);
c = result.charAt(j);
count = 1;
}
}
sb.append(count);
sb.append(c);
result = sb.toString();
}
}
return result;
}
}
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1is read off as
"one 1"or
11.
11is read off as
"two 1s"or
21.
21is 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.
【思路】
没有使用什么技巧,两层循环,1到n循环,内层依次扫描上一层数字。
【code】
public class Solution {
public String countAndSay(int n) {
if (n < 0) {
return null;
}
String result = "1";
StringBuffer sb = null;
if (n == 1) {
return result;
} else {
for (int i = 2; i <= n; i++) {
sb = new StringBuffer();
int count = 0;
char c = result.charAt(0);
for (int j = 0; j < result.length(); j++) {
if (result.charAt(j) == c) {
count++;
} else {
sb.append(count);
sb.append(c);
c = result.charAt(j);
count = 1;
}
}
sb.append(count);
sb.append(c);
result = sb.toString();
}
}
return result;
}
}
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解