[LeetCode 38] Count and Say
Posted yangykaifa
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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);
以上是关于[LeetCode 38] Count and Say的主要内容,如果未能解决你的问题,请参考以下文章