Count and Say

问题:链接

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.

解答:

没啥意思,数数吧。m_itoa()是自己实现的一个一位的itoa

代码:

class Solution {
public:
    string countAndSay(int n) {
    
	if(n == 0)
		return "";
	string s = "1";
	for(int i = 1; i < n; i++)
	{
		s = next(s);
	}
	return s;
	
}

	string next(string ls)
	{
		int count;
		char target;
		string temp;
		count = 1;
		target = ls[0];
		string s = "";
		for(int i = 1; i < ls.size(); i++)
		{
			if(target == ls[i])
				++count;
			else
			{
				temp = m_itoa(count);
				s += temp;
				s += target;
				count = 1;
				target = ls[i];
			}
		}
		temp = m_itoa(count);
		s += temp;
		s += target;
		return s;
	}
	string m_itoa(int count)
	{
		string re = "";
		stack<int> st;
		char s[2];
		while(count)
		{
			st.push(count%10);
			count /= 10;
		}
		while(!st.empty())
		{
			s[0] = st.top() + '0';
			s[1] = '\0';
			re.append(s);
			st.pop();
		}
		return re;
	}
};


posted @ 2017-07-25 12:04  zsychanpin  阅读(115)  评论(0编辑  收藏  举报