zoukankan      html  css  js  c++  java
  • [LeetCode 38] 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.

    Idea:Based on the string of previous string, count the digits, then the string will be the # + digits

    1. get the count-and-say sequence

    2. count the number of the same continuous digits.

    3. form the number of digits following by digit string. 

    4. return the string. 

    class Solution {
    public:
        string countAndSay(int n) {
            if(n <= 0) return "";
            if(n == 1) return "1";
            
            string result = "1";      // used to store result;
            int flag = 1;      //set a flag to show the number.
            while(flag++ < n){
                //flag++; // used to sign the round of loop
                
                int count = 1;
                int i = 0;
                int j = i;
                string temp;
                do{
                    j++;
                    
                    if(result[i] == result[j]) count++;
                    else{
                        temp += '0' + count;
                        temp += result[i];
                        i = j;
                        count = 1;//each time need to reset to 1;
                        }
                    
                }while(j < result.size());
                
                result = temp; 
            }
            
            return result;
        }
    };                                                                                                                                                                               

    Covert the number to char tips: 

    (1) char c = '0' + digit;

    (2) C++, char c = to_string(digit); 



  • 相关阅读:
    win10的power shell可以学习少部分linux命令_功能与cmd类似
    js数组的初始化
    Vue.js 学习笔记
    jquery knob旋钮插件
    jquery 城市三级联动
    xampp 配置虚拟主机
    2016 360 前端开发 面经
    2016 乐视 前端开发 面经
    主流浏览器内核及前缀
    前端代码优化方法
  • 原文地址:https://www.cnblogs.com/yangykaifa/p/6718347.html
Copyright © 2011-2022 走看看