leetcode刷题日记——Count and Say

来源:互联网 发布:软件系统测试 编辑:程序博客网 时间:2024/06/13 20:34
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.

问题分析:题目所要实现的目标就是后一个字符串是对前一个字符串的计数。给定一个n,返回序列的第n个元素。注意到题目不仅仅是统计各种元素的个数,当序列中元素发生改变的同时,需要重新计数。这一点很重要。其他操作都比较好理解。另外因为最终要将计数值的整数形转化为字符串然后用+号连接起来生成新的字符串,to_string 方法的使用,具体实现代码如下:

class Solution {public:    string countAndSay(int n) {     if (n<2) return "1";string pre = "1";map<char, int> count;for (int i = 1; i<n; i++){int length = pre.size();int count = 1;char xx = pre[0];string ss = "";for (int j = 1; j<length; j++){if (pre[j] == xx) count++;else{ss += to_string(count);ss += xx;xx = pre[j];count = 1;}}ss += to_string(count);ss += xx;pre = ss;}return pre;    }   };


0 0
原创粉丝点击