[leetcode] 38. Count and Say解題レポート
1689 ワード
タイトルリンク:https://leetcode.com/problems/count-and-say/
The count-and-say sequence is the sequence of integers beginning as follows:
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
構想:本題の意味は1つのカウント+文字で1つの数字を符号化して、それからカウント+文字で前の結果を符号化して、このように1つのシーケンスを形成します.最後に結果を文字列に保存します.
整数と文字列の間の変換に関連するため、STLは各タイプの変換に特化したクラスstringstreamを提供し、このクラスがあれば母はタイプ間の変換を心配する必要はありません.
コードは次のとおりです.
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.
構想:本題の意味は1つのカウント+文字で1つの数字を符号化して、それからカウント+文字で前の結果を符号化して、このように1つのシーケンスを形成します.最後に結果を文字列に保存します.
整数と文字列の間の変換に関連するため、STLは各タイプの変換に特化したクラスstringstreamを提供し、このクラスがあれば母はタイプ間の変換を心配する必要はありません.
コードは次のとおりです.
#incldue <stdlib.h>
class Solution {
public:
string countAndSay(int n) {
string result = "1";
int cnt = 1;
while(cnt < n)
{
stringstream tem;//c++ stl
char old = '#';
int num = 0;
for(int i = 0; i <result.size() ; i++)
{
if(result[i] != old)//
{
if(old != '#')//
tem << num << old;
num = 1;
old = result[i];
}
else// , 1
num++;
}
tem << num << old;//
tem >> result;//
cnt++;
}
return result;
}
};