码迷,mamicode.com
首页 > 其他好文 > 详细

【字符串】1221. 分割平衡字符串

时间:2020-05-04 00:41:00      阅读:51      评论:0      收藏:0      [点我收藏+]

标签:--   div   技术   balance   前缀和   前缀   返回   color   相等   

题目:

技术图片

 

 

 

解答:

把L看作1,R看作-1,构建前缀和,当前缀和为0时,说明LR个数相等。返回前缀和中0的个数。

 1 class Solution {
 2 public:
 3     int balancedStringSplit(string s) 
 4     {
 5         if (s.size() < 2) 
 6         {
 7             return 0;
 8         }
 9 
10         int res = 0;
11         int count = 1;
12     
13         if (s[0] == R)
14          {
15             count = -1;
16         }
17     
18         for (int  i = 1; i < s.size(); i++)
19         {
20             if (R == s[i])
21             {
22                 count--;
23             }
24             else if (L == s[i])
25             {
26                 count++;
27             }
28             if (count == 0)
29             {
30                 res++;
31             }  
32         } 
33 
34         return res;
35     }
36 };

 

【字符串】1221. 分割平衡字符串

标签:--   div   技术   balance   前缀和   前缀   返回   color   相等   

原文地址:https://www.cnblogs.com/ocpc/p/12824551.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!