leetcode 038 —— Count and Say

来源:互联网 发布:意外的sql命令结尾 编辑:程序博客网 时间:2024/05/17 08:39

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 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 sequence.

Note: The sequence of integers will be represented as a string.


思路:


class Solution {public:string countAndSay(int n) {string s ;s = s + '1';for (int i = 1; i <n; i++){int j = 0;int cnt = 0;while (j < s.size()){if (j == s.size() - 1){s.insert(j, 1,'1');break;}cnt = 0;while (j + cnt +1 < s.size() && s[j ] == s[j + cnt + 1]){cnt++;   //cnt代表要删除的位数}s.erase(j, cnt);s.insert(j,1, char(cnt+1 + '0'));j = j + 2;}}return s;}}a;


0 0
原创粉丝点击