首页 > 其他 > 详细

[LeetCode 38] Count and Say

时间:2017-04-16 13:29:02      阅读:257      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!