周赛158:分割平衡字符串

  简单的计数题,比赛的时候瞎了眼,题目如下

  很明显的计数题,没啥好讲的。题目里说了,输入的一定时平衡字串,那么就不会出现LLLRRLLL这种情况。所以我们同时记录L和R的出现次数,只要相等,就代表可以切割,相等了多少次,就代表可以切成多少份。不理解,可以自行列一列。其他的没什么特别恶心的地方,我就直接贴代码了(这次的题用的都是C++)

 1 /**
 2  * @brief   leetcode 158.1
 3  * @note    C++
 4  * @anuthor 杨文蓁的小迷弟
 5  */
 6 class Solution
 7 {
 8 public:
 9     int balancedStringSplit(string s)
10     {
11         int len = s.length();
12         int R_cnt = 0, L_cnt = 0, cnt = 0;
13         for (int i = 0; i < len; i++)
14         {
15             if ('R' == s[i])
16             {
17                 R_cnt++;
18             }
19             else
20             {
21                 L_cnt++;
22             }
23             if (L_cnt == R_cnt)
24             {
25                 cnt++;
26             }
27         }
28         return cnt;
29     }
30 };

  

  周赛不易,诸君共勉!

猜你喜欢

转载自www.cnblogs.com/daker-code/p/11673302.html