#leetCode brush title documentary Day12

https://leetcode-cn.com/problems/split-a-string-in-balanced-strings/

In a "balanced string", the number of 'L' and 'R' character is the same.

Given a balanced string s, you divide it into as many balance strings.

Returns the maximum number of equilibrium can be obtained by a division of the string.

 

Example 1:

Input: s = "RLRRLLRLRL"
Output: 4
explains: S may be divided into "RL", "RRLL", "RL", "RL", each sub-string contains the same number of 'L' and 'R'.
Example 2:

Input: s = "RLLLLRRRLR"
Output: 3
explains: S may be divided into "RL", "LLLRRR", "LR", each sub-string contains the same number of 'L' and 'R'.
Example 3:

Input: s = "LLLLRRRR"
Output: 1
explains: S can remain as "LLLLRRRR".
 

prompt:

1 <= s.length <= 1000
s[i] = 'L' 或 'R'

 

Chicken dishes to try:

After reading the title thinking: obviously greedy, what auxiliary data structure needs? Stack? queue? (Do not seem to feel should be O (n) can be solved)

Thus began the handwritten

 

 1 class Solution {
 2 public:
 3     int balancedStringSplit(string s) {
 4         int len = s.length();
 5         int left = 0;
 6         int right = 0;
 7         int num = 0;
 8         for (int i = 0; i < len; i ++) {
 9             if (s[i] == 'R') right ++;
10             if (s[i] == 'L') left ++;
11             if (left == right && left != 0) {
12                 left = 0;
13                 right = 0;
14                 num ++;
15             }
16         }
17         return num;
18     }
19 };

 

Very quickly through the sample again, thinking for a moment should be no special circumstances not considered, then! submit!

Double hundred too!

 

 

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/split-a-string-in-balanced-strings
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

Guess you like

Origin www.cnblogs.com/xyy999/p/11827432.html