38、Count and Say

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"

C+

class Solution {
public:
string countAndSay(int n) {
if (n == ) return "";
string res = "";
while (--n) {
string cur = "";
for (int i = ; i < res.size(); i++) {
int count = ;
while ((i + < res.size()) && (res[i] == res[i + ])){
count++;
i++;
}
cur += to_string(count) + res[i];
}
res = cur;
}
return res;
}
};

python

Solution 1 ... using a regular expression
def countAndSay(self, n):
s = ''
for _ in range(n - 1):
s = re.sub(r'(.)\1*', lambda m: str(len(m.group(0))) + m.group(1), s)
return s
Solution 2 ... using a regular expression
def countAndSay(self, n):
s = ''
for _ in range(n - 1):
s = ''.join(str(len(group)) + digit
for group, digit in re.findall(r'((.)\2*)', s))
return s
Solution 3 ... using groupby
def countAndSay(self, n):
s = ''
for _ in range(n - 1):
s = ''.join(str(len(list(group))) + digit
for digit, group in itertools.groupby(s))
return s

最新文章

  1. 如何快速从一个Storage Account拷贝到另一个账号
  2. Android高工必备技能
  3. C# 参数化SQL语句中的like和in
  4. solr 导入数据
  5. C# winform 弹出输入框
  6. Calendar 类的应用
  7. PhotoShop常用快捷键(1)
  8. 重温Java的类加载机制
  9. openwrt time sycronize
  10. SDWebImage缓存
  11. 我读《通过Go来处理每分钟达百万的数据请求》
  12. readfile &amp; file_get_contents异同
  13. BZOJ-1045-[HAOI2008] 糖果传递(中位数原理)
  14. Python中capitalize()与title()的区别
  15. Git分支合并冲突解决
  16. 【学习笔记】JS知识点整理
  17. npm 更新版本
  18. [总结]jQuery之选择器集合
  19. 2017-09-21xlVBA_蒸发SQL循环查询1
  20. windows10下安装source insight 4.0(破解版)

热门文章

  1. 03-python 学习第三天:文件操作
  2. 关于mybatis对实体类参数绑定参数的问题
  3. spring boot 项目添加maven依赖时provided
  4. windows 遍历目录下的所有文件 FindFirstFile FindNextFile
  5. [Swoole系列入门教程 1] CentOs 上的Swoole安装
  6. List--列表合成
  7. JZOJ5883【NOIP2018模拟A组9.25】到不了——动态LCA裸题
  8. RN 环境搭建 运行demo App
  9. 深入浅出 Java Concurrency (3): 原子操作 part 2[转]
  10. Java虚拟机系列(四)---查看GC日志