在 C++ 中执行给定操作后的最终字符串
在本教程中,我们将解决以下问题。
给定一个仅包含字符 a 和 b 的字符串,我们的任务是从字符串中删除子字符串**ab**。并打印剩余的字符串。
这里,解决问题的思路非常简单。最终,每个仅包含 a 和 b 的字符串都将缩减为 a 或 b。
让我们看看解决问题的步骤。
初始化字符串。
为 a 和 b 初始化两个计数器变量。
遍历给定的字符串。
计算 a 和 b 的数量。
找到 a 和 b 频率中的最大值。
打印两者之间的差值。
示例
让我们看看代码。
#include <bits/stdc++.h>
using namespace std;
string getTheUpdatedString(string str) {
int n = str.length();
int a_count = 0, b_count = 0;
for (int i = 0; i < n; i++) {
if (str[i] == 'a') {
a_count++;
}
else {
b_count++;
}
}
string updated_string = "";
if (a_count > b_count) {
for (int i = 0; i < a_count - b_count; i++) {
updated_string += "a";
}
}
else {
for (int i = 0; i < b_count - a_count; i++) {
updated_string += "b";
}
}
return updated_string;
}
int main() {
string str = "ababababaaa";
cout << getTheUpdatedString(str) << endl;
}输出
如果运行以上代码,则会得到以下结果。
aaa
结论
如果您在本教程中有任何疑问,请在评论区提出。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP