Count and Sayは、前の数列のRun-Length Encoding(RLE)を行うことで次の数列を生成する反復的なシーケンスです。
ステップ1: 文字 "2" を1回カウント → "12"
ステップ2: 文字 "1" を1回カウント → "11"
結果: "12" + "11" = "1211"
ステップ1: 文字 "1" を3回カウント → "31"
ステップ2: 文字 "2" を1回カウント → "12"
結果: "31" + "12" = "3112"
/**
* Count and Say数列のn番目の要素を返す関数
* @param {number} n - 取得したい数列の位置(1以上30以下)
* @returns {string} n番目のcount-and-say数列の文字列
*/
function countAndSay(n: number): string {
let current: string = "1";
if (n === 1) return current;
for (let i: number = 2; i <= n; i++) {
current = runLengthEncode(current);
}
return current;
}
/**
* Run-Length Encoding実装
* @param {string} str - エンコードする文字列
* @returns {string} エンコード後の文字列
*/
function runLengthEncode(str: string): string {
let result: string = "";
let count: number = 1;
let currentChar: string = str[0];
for (let i: number = 1; i < str.length; i++) {
if (str[i] === currentChar) {
count++;
} else {
result += count + currentChar;
currentChar = str[i];
count = 1;
}
}
result += count + currentChar;
return result;
}
nの値を入力してcount-and-sayシーケンスを生成してください: