在 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
結論
如果您在本教程中有任何疑問,請在評論區提出。
廣告