Leetcode_count-and-say(c++ and python version)
2014-04-14 16:42
387 查看
地址:http://oj.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.
思路:模拟题。
参考代码:
参考代码二,记录字符和该字符个数,不要忘记最后一次的记录
Python
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.
思路:模拟题。
参考代码:
class Solution { public: string countAndSay(int n) { string str; if(!n) return str; str = "1"; int len, cnt; char ch; queue<string>q; for(int i = 1; i<n; ++i) { len = str.length(); cnt = 0; ch = str[0]; for(int j = 0; j<len; ++j) { if(str[j]==ch) ++cnt; else { string tmp; tmp += char(cnt+'0'); tmp += ch; q.push(tmp); cnt = 1; ch = str[j]; } } string tmp; tmp += char(cnt+'0'); tmp += ch; q.push(tmp); tmp.clear(); while(!q.empty()) { tmp+=q.front(); q.pop(); } str = tmp; } return str; } };
参考代码二,记录字符和该字符个数,不要忘记最后一次的记录
class Solution { public: string countAndSay(int n) { string newStr, str = "1"; char ch; int cnt; for(int i = 1; i<n; ++i) { newStr = ""; ch = str[0]; cnt = 1; for(int j = 1; j<str.length(); ++j) { if(str[j]==ch) ++cnt; else { newStr += (cnt+'0'); newStr += ch; ch = str[j]; cnt = 1; } } newStr += (cnt+'0'); newStr += ch; str = newStr; } return str; } };
Python
class Solution: # @return a string def countAndSay(self, n): s = "1" for i in range(1, n): ch = s[0] cnt = 1 news = "" for j in range(1, len(s)): if ch == s[j] : cnt += 1 else : news += (str(cnt) + ch) ch = s[j] cnt = 1 news += (str(cnt) + ch) s = news return s
相关文章推荐
- effective c++ 读书笔记
- 一道C语言编程比赛题(时钟追赶问题)
- C语言 时间函数
- 将Vim改造为强大的IDE—Vim集成Ctags/Taglist/Cscope/Winmanager/NERDTree/OmniCppComplete(有图有真相)
- PAT 1073. Scientific Notation (科学计数法 字符串模拟)
- VC++中加入语音wav最简单的方法
- 【Visual C++】Windows GDI贴图闪烁解决方法
- C++primer plus第六版课后编程题答案10.3
- C++primer plus第六版课后编程题答案10.3
- [一站式服务] Windows下C++文件编译.so 文件
- C6000的C语言优化
- C++的存储持续性(自动、静态、动态),作用域,链接性
- dsp C语言优化-(三)
- C++ - 虚函数(virtual function)缺省参数的异常表现 及 正确使用方法
- C++ 全排列函数 std::next_permutation与std::prev_permutation
- DSP C语言优化-(二)
- C++类型不安全
- DirectX 11 Compute Shader tutorial
- 【C/C++多线程编程之二】pthread简介
- i = i++;