【Leetcode】Count and Say
2016-06-01 20:07
316 查看
题目链接:https://leetcode.com/problems/count-and-say/
题目:
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.
思路:
题目看懂了就好做了。。
算法:
public String countAndSay(int n) {
String r = "1";
for (int i = 1; i < n; i++) {
String t = "";
int count = 0;
String flag = r.charAt(0) + "";
for (int j = 0; j < r.length(); j++) {
if ((r.charAt(j) + "").equals(flag)) {
count++;
} else {
t += count + "" + flag;
flag = r.charAt(j) + "";
count = 1;
}
}
t += count + "" + flag;
r = t;
}
return r;
}
题目:
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.
思路:
题目看懂了就好做了。。
算法:
public String countAndSay(int n) {
String r = "1";
for (int i = 1; i < n; i++) {
String t = "";
int count = 0;
String flag = r.charAt(0) + "";
for (int j = 0; j < r.length(); j++) {
if ((r.charAt(j) + "").equals(flag)) {
count++;
} else {
t += count + "" + flag;
flag = r.charAt(j) + "";
count = 1;
}
}
t += count + "" + flag;
r = t;
}
return r;
}
相关文章推荐
- ECC
- TCP管理的4种定时器
- ActiveMQ 的安装(单节点)
- {算法}YY矩阵乘法
- 彻底理解:阻塞、非阻塞、同步、异步、Reactor、Proactor
- UVA - 11991 Easy Problem from Rujia Liu?【STL】
- POJ 1061 青蛙的约会(扩展欧几里得算法)
- Semaphore示例
- Kafka Topic Partition Replica Assignment实现原理及资源隔离方案
- 更新UI 2种方法
- zzulioj1873: This offer 深搜
- 每日scrum(4)
- [转]定位占用oracle数据库cpu过高的sql
- LeetCode-347.Top K Frequent Elements
- 图片下载
- Linux的文件权限
- Flume 数据采集系统 性能优化和关键问题汇总
- XML解析(xstream)第三方
- 每日Scrum(4)
- paramiko多进程同步目录