[Simple Algorithm] 19. Count and say

topic:

A sequence of numbers refers to a sequence of integers, and the numbers are counted in the order of the integers to obtain the next number. The first five items are as follows:

1 .      1 
2 .      11 
3 .      21 
4 .      1211 
5 .      111221 
1 is pronounced   " one 1 "   ( " one one " ), which is 11 .
11 is pronounced " two 1s " ( " two ones " ), which is 21 .
21 is pronounced " one 2 " ,   " one 1 " ( " one two " ,   "A one " ), i.e. 1211 .

Given a positive integer n, output the nth item of the count sequence.

Note: Integer order will be represented as a string.

Example 1 :

Input: 1 
Output: " 1 " 
Example 2 :

Input: 4 
Output: " 1211 "

1. Problem solving ideas:

Count the number of numbers in the string and form a new string. The next loop continues to count the number of characters in the new string.

class Solution {
public:
    string countAndSay(int n) {
        string str = "1";
        
        for(int i = 2;i <= n; ++i){
            string tmp = "";
            int start = 0;
            int cnt = 0;
            for(int j = 0;j < str.size(); ++j){
                if(str[j] == str[start]){
                    cnt++;
                }else{
                    tmp += to_string(cnt) + str[start];
                    start = j;
                    cnt = 1;
                }
            }
            tmp += to_string(cnt) + str[start];
            str = tmp;
        }
        
        return str;
    }
};

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325205334&siteId=291194637