Skip to content

Commit b82b932

Browse files
committed
feat: finish 1341
1 parent d7f1932 commit b82b932

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed
+93
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
# 1341. Split a String in Balanced Strings
2+
3+
- Difficulty: Easy.
4+
- Related Topics: String, Greedy, Counting.
5+
- Similar Questions: .
6+
7+
## Problem
8+
9+
**Balanced** strings are those that have an equal quantity of ```'L'``` and ```'R'``` characters.
10+
11+
Given a **balanced** string ```s```, split it into some number of substrings such that:
12+
13+
14+
15+
- Each substring is balanced.
16+
17+
18+
Return **the **maximum** number of balanced strings you can obtain.**
19+
20+
 
21+
Example 1:
22+
23+
```
24+
Input: s = "RLRRLLRLRL"
25+
Output: 4
26+
Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'.
27+
```
28+
29+
Example 2:
30+
31+
```
32+
Input: s = "RLRRRLLRLL"
33+
Output: 2
34+
Explanation: s can be split into "RL", "RRRLLRLL", each substring contains same number of 'L' and 'R'.
35+
Note that s cannot be split into "RL", "RR", "RL", "LR", "LL", because the 2nd and 5th substrings are not balanced.
36+
```
37+
38+
Example 3:
39+
40+
```
41+
Input: s = "LLLLRRRR"
42+
Output: 1
43+
Explanation: s can be split into "LLLLRRRR".
44+
```
45+
46+
 
47+
**Constraints:**
48+
49+
50+
51+
- ```2 <= s.length <= 1000```
52+
53+
- ```s[i]``` is either ```'L'``` or ```'R'```.
54+
55+
- ```s``` is a **balanced** string.
56+
57+
58+
59+
## Solution
60+
61+
```javascript
62+
/**
63+
* @param {string} s
64+
* @return {number}
65+
*/
66+
var balancedStringSplit = function(s) {
67+
var num = 0;
68+
var S = 0;
69+
var L = 0;
70+
for (var i = 0; i < s.length; i++) {
71+
if (s[i] === 'L') {
72+
L++;
73+
} else {
74+
S++;
75+
}
76+
if (S === L) {
77+
num++;
78+
S = 0;
79+
L = 0;
80+
}
81+
}
82+
return num;
83+
};
84+
```
85+
86+
**Explain:**
87+
88+
Every time you meet a balanced string, split it.
89+
90+
**Complexity:**
91+
92+
* Time complexity : O(n).
93+
* Space complexity : O(1).

0 commit comments

Comments
 (0)