zoukankan      html  css  js  c++  java
  • leetcode 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.

    Subscribe to see which companies asked this question

     
     
    从十七号早晨想了十七号一天,今天早上也在想。就这么一道题。就是没想出来,这种挫败感。
    用vector想了,栈想了,列表都想了,却单单没有想简单的用string实现。
     
    首先,扫描一个字符串,然后把次数和字符按顺序加入到一个新的字符串中,应该是一个独立函数的功能。
    其次,n应该是执行这个函数的一个循环次数,初始的字符串应该是“1”
     
    学习了~~以后这种题要注意。
    class Solution {
    public:
        string Ustring(string s){   //扫描一个字符串,
            int count=1;
            string ret;
            char tmp;
            char stmp=s[0];
            for(int i=1;i<s.length();i++){
                if(s[i]==stmp) {
                    count++;
                }else {
                    tmp=count+'0';
                    ret=ret+tmp+stmp;
                    stmp=s[i];
                    count=1;
                }
            }
            tmp=count+'0';
            ret=ret+tmp+stmp;
            return ret;
        }
        
        string countAndSay(int n) {
            string s="1";
            for(int i=1;i<n;i++){
                s=Ustring(s);
            }
            return s;
            
        }
    };
     
  • 相关阅读:
    Python学习————并发编程
    Python学习————作业
    Python学习————网络编程
    Python学习————异常处理
    Python学习————反射
    Python学习————绑定方法
    Python学习————继承
    1765 谷歌的恐龙
    2504 是子序列的个数
    51Nod2386 分则能成
  • 原文地址:https://www.cnblogs.com/LUO77/p/5058276.html
Copyright © 2011-2022 走看看