使用 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