您的位置:首页 > 其它

Count and Say-LeetCode

2014-10-22 15:04 218 查看
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.

用到了一个平时没有用到的stringstream,用来将int转化为string,十分便捷,使用方法见下面的博文链接。

http://www.cppblog.com/Sandywin/archive/2007/07/13/27984.html

代码:

class Solution {
public:
    string getnextstr(string str)
    {
    	stringstream ss;
    	char key =  str[0];
     	char current = str[0];
    	int count = 0;

    	for (int i = 0; i < str.length(); i++)
    	{
    		current = str[i];
    		if (key == current)
    		{
    			count++;
     			
	    	}
    		else
    		{
	    		ss<<count<<key;
	    		key = current;
	    		count = 1;
	    	}
    	}
    	ss<<count<<key;
    	return ss.str();
    }

    string countAndSay(int n) {
    	string result = "1";
    	if ( n <= 0)
    	{
    		return NULL;
    	}
    	if (n == 1)
      	{	
	    	return result;
    	}
    	for (int i = 0; i < n - 1; i++)
    	{
    		result = getnextstr(result);
    	}
    	return result;

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