Программы на C++. Форум разработчиков
Гость
Написать код на C++, который преобразует строку AAABCDEFOOOOOOO в (3)A(-5)BCDEF(6)O
Сообщение
Гость » 30 апр 2024, 04:31
Я написал код, но не понимаю, почему так получается, что он выдает перед разными буквами (-1), а не считает и потом записывает все сразу "(-5)BCDEF". Пожалуйста, помогите мне.
Код: Выделить всё
#include
#include
using namespace std;
string compressString(const string input) {
string compressedString;
string reservedstring;
char currentChar = input[0];
int count = 1;
for (int i = 1; i < input.length(); i++) {
if (input[i] == currentChar) {
count++;
}
else {
if (count > 1) {
compressedString += "(" + to_string(count) + ")" + currentChar;
}
else {
compressedString += "(-" + to_string(count) + ")" + currentChar;
}
currentChar = input[i];
count = 1;
}
}
if (count > 1) {
compressedString += "(" + to_string(count) + ")" + currentChar;
}
else {
compressedString += "(-" + to_string(count) + ")" + currentChar;
}
return compressedString;
}
int main() {
string input = "AAABCDEFOOOOOO";
string compressed = compressString(input);
cout
Подробнее здесь: [url]https://stackoverflow.com/questions/78403743/write-c-code-that-turns-the-string-aaabcdefoooooo-into-3a-5bcdef6o[/url]
1714440692
Гость
Я написал код, но не понимаю, почему так получается, что он выдает перед разными буквами (-1), а не считает и потом записывает все сразу "(-5)BCDEF". Пожалуйста, помогите мне. [code]#include #include using namespace std; string compressString(const string input) { string compressedString; string reservedstring; char currentChar = input[0]; int count = 1; for (int i = 1; i < input.length(); i++) { if (input[i] == currentChar) { count++; } else { if (count > 1) { compressedString += "(" + to_string(count) + ")" + currentChar; } else { compressedString += "(-" + to_string(count) + ")" + currentChar; } currentChar = input[i]; count = 1; } } if (count > 1) { compressedString += "(" + to_string(count) + ")" + currentChar; } else { compressedString += "(-" + to_string(count) + ")" + currentChar; } return compressedString; } int main() { string input = "AAABCDEFOOOOOO"; string compressed = compressString(input); cout Подробнее здесь: [url]https://stackoverflow.com/questions/78403743/write-c-code-that-turns-the-string-aaabcdefoooooo-into-3a-5bcdef6o[/url]