使用 C++ 將字串拆分為平衡字串
我們知道平衡字串具有相同數量的左字元和右字元。假設我們有一個平衡字串 s,將其拆分為最大數量的平衡字串。我們必須返回拆分的平衡字串的最大數量。因此,如果字串為 “RLRRLLRLRL”,則輸出將為 4。因為有四個平衡字串。“RL”、“RRLL”、“RL”和“RL”,每個子字串具有相同數量的 L 和 R。
要解決此問題,我們將按照以下步驟進行操作 -
- 初始化 cnt := 0,ans := 0
- 對於 i := 0 到字串的大小
- cnt := 0
- 對於 j := i 到字串的大小 -
- 如果 s[j] = ‘R’,則 cnt 增加 1,否則減少 cnt
- 如果 j - i > 0 且 cnt = 0,則 ans 增加 1,i := j,然後中止迴圈
- 返回 ans
示例
讓我們看以下實現以更好地理解 -
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int balancedStringSplit(string s) {
int cnt = 0;
int ans = 0;
for(int i =0;i<s.size();i++){
cnt = 0;
for(int j = i;j<s.size();j++){
if(s[j] == 'R')cnt++;
else cnt--;
if(j-i>0 && cnt == 0 ){
ans++;
i=j;
break;
}
//cout << i << " " << j <<" "<< cnt << endl;
}
}
return ans;
}
};
main(){
Solution ob;
cout << ob.balancedStringSplit("RLLLLRRRLR");
}輸入
"RLLLLRRRLR"
輸出
3
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP