/
DeC2018
/
0038
Обзор
Документация
Войти
/
DeC2018
/
0038
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
main.cpp
57 строк
2 KB
Den
create main.cpp
19 янв 2025, 21:46
19 янв 2025, 21:46
8e583fc
Код
Авторство
О чём код?
#include <iostream> #include <string> class Solution { public: std::string countAndSay(int n) { // Base case: if n is 1, return the initial sequence "1" if (n == 1) return "1"; // Start with the first sequence std::string s = "1"; // Generate the sequence iteratively up to the nth sequence for (int i = 2; i <= n; i++) { const int len = s.size(); // Length of the current sequence std::string t; t.reserve(len << 1); // Reserve space to minimize reallocations // Process the current sequence to build the next one for (int j = 0; j < len;) { char c = s[j]; // Current character to count int count = 1; // Start counting occurrences // Count consecutive characters while (j + count < len && s[j + count] == c) count++; // Append the count and the character to the new sequence t.push_back('0' + count); // Convert count to character t.push_back(c); // Move to the next character group j += count; } // Update the current sequence to the newly generated one s = std::move(t); } // Return the nth sequence return s; } }; int main() { Solution solution; // Test case 1: n = 4 int n1 = 4; std::string result1 = solution.countAndSay(n1); std::cout << "Input: n = " << n1 << " | Output: \"" << result1 << "\"" << std::endl; // Test case 2: n = 1 int n2 = 1; std::string result2 = solution.countAndSay(n2); std::cout << "Input: n = " << n2 << " | Output: \"" << result2 << "\"" << std::endl; return 0; }