zoukankan      html  css  js  c++  java
  • 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] = '';
    			re.append(s);
    			st.pop();
    		}
    		return re;
    	}
    };


  • 相关阅读:
    Linux 文件权限
    spak数据倾斜解决方案
    逻辑时钟
    kafka入门
    深入学习MySQL事务:ACID特性的实现原理
    程序员的诗
    java技术突破要点
    一个请求过来都经历了什么
    如何保持长时间高效学习
    你的系统如何支撑高并发
  • 原文地址:https://www.cnblogs.com/zsychanpin/p/7233326.html
Copyright © 2011-2022 走看看