您的位置:首页 > 其它

leetcode 38:count and say

2016-02-25 09:46 405 查看

问题描述:

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.

思路:

题目主要是涉及到字符串和整型之间的转换等等,而解题思路是很直接的,就是读取当前字符串,产生下一个字符串。而产生字符串的处理中,每读入一个字符可以分为三种情况:

1. 在这个数字之前,record没有记录数字,所以设立新的record值,开始计数;

2. 这是一个和前一个record相同的数,计数加一;

3. 这是一个新的数字,和前面record不同,所以要将前面的record和count转换后存进新的字符串中,然后将record和count重置为0状态,并且将循环下标i减一,因为当前数字还没有处理,留待下一循环处理。

其实这里涉及一些直观的观察和猜测:不会产生超过10个xx数(
1111111111
)的情况,这个可以通过在leetcode系统测试样例试验即可做出猜测,而大略可知,当出现
1111
时,前一个字符串就应该将“one 1,one 1”这种情况读为“two 1”,因而不会出现
4
这个数字。所以产生10个xx数这样不知怎么读的情况是没有的。

代码中主要使用了stringstream来将int转换成string,非常好用,只需流进流出即可,不过不知道这样转换的程序代价是不是会高些,需实验。

代码:

class Solution {
public:
string countAndSay(int n) {
string result = "1";   //初始字符串从1开始
string s;
for (int i = 1; i < n; i++)
{
s = gennext(result);    //第n个字符串由第n-1个字符串产生,所以从1开始循环n-1次产生第n个
result = s;
}
return result;
}

//function: generate the next string from the current string
string gennext(string s)
{
string next = "";
int record = 0, count = 0, now = 0;
int size = s.size();

for (int i = 0; i < size; i++)
{
now = s[i] - '0';
if (record == 0)    //a new integer
{
record = now;
count = 1;
}
else if(record == now)  //count the now
{
count++;
}
else   //the previous subarray is interrupted, add the record and count to the "next" string
{
string a;
stringstream ss;
//convert int to string
ss << count;
ss >> a;
next += a;
ss.clear();
ss << record;
ss >> a;
next += a;
//flush to 0
record = 0;
count = 0;
//read the current i again.
i--;
}
}

//deal with the previous subarray the same as the interrupted situation
string a;
stringstream ss;
ss << count;
ss >> a;
next += a;
ss.clear();
ss << record;
ss >> a;
next += a;

return next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: