码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode 38] Count and Say

时间:2017-04-16 13:28:21      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:present   margin   over   return   tom   style   turn   oop   mon   

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); 



[LeetCode 38] Count and Say

标签:present   margin   over   return   tom   style   turn   oop   mon   

原文地址:http://www.cnblogs.com/yangykaifa/p/6718347.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!