在C ++中的平衡字符串中分割字符串

众所周知,平衡弦是指具有相等数量的左右字符的弦。假设我们有一个平衡字符串s将其拆分为最大数量的平衡字符串。我们必须返回拆分后的平衡字符串的最大数量。因此,如果字符串为“ RLRRLLRLRL”,则输出为4。因为有四个平衡字符串。每个子串的“ RL”,“ RRLL”,“ RL”和“ RL”具有相等的L和R。

为了解决这个问题,我们将遵循以下步骤-

  • 初始化cnt:= 0和ans:= 0

  • 对于我:= 0到字符串的大小

    • 如果s [j] ='R',则将cnt加1,否则将cnt减1

    • 如果j – i> 0且cnt = 0,则将ans加1,i:= j,并中断循环

    • cnt:= 0

    • 对于j:= i到字符串的大小-

    • 返回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