leetcode #38 in cpp

来源:互联网 发布:php学生管理系统 编辑:程序博客网 时间:2024/06/05 23:41

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.

Solution: 

for 1 to n: 

Set current string = "";

Given a string, count the frequency of every unique number. Then append the (frequency in string) + (the number in string) to current string.  


Code: 

class Solution {public:    string countAndSay(int n) {        string s = "1";               return count_and_say(s,n);    }    string count_and_say(string s, int n){        if(n == 1) return s;        vector<int> count;//count the frequencies of the unique numbers         vector<char> real_num;//record the unique numbers in the string        int temp_count = 0;        for(int i = 0; i < s.length(); i ++){            if(i==0 || s[i] == s[i-1]) temp_count ++;//if the same or it is the head of the string, count + 1            else{                count.push_back(temp_count);//if not the same, we are done with this number.record its count                real_num.push_back(s[i-1]);//record this number                temp_count = 1;            }        }        count.push_back(temp_count);        real_num.push_back(s[s.length() - 1]);        string res = "";        for(int i = 0; i < count.size(); i++){            res += '0' + count[i];//say count first            res += real_num[i];//say the number        }        return count_and_say(res,n-1);            }};


0 0