-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSplitAStringInBalancedStrings.java
More file actions
54 lines (50 loc) · 1.65 KB
/
SplitAStringInBalancedStrings.java
File metadata and controls
54 lines (50 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package array;
/**
* @author :DengSiYuan
* @date :2019/11/6 18:50
* @desc : 1221.分割平衡字符串
* 【题目】
* 在一个「平衡字符串」中,'L' 和 'R' 字符的数量是相同的。
* 给出一个平衡字符串 s,请你将它分割成尽可能多的平衡字符串。
* 返回可以通过分割得到的平衡字符串的最大数量。
* 【示例】
* 示例 1:
* 输入:s = "RLRRLLRLRL"
* 输出:4
* 解释:s 可以分割为 "RL", "RRLL", "RL", "RL", 每个子字符串中都包含相同数量的 'L' 和 'R'。
* 示例 2:
* 输入:s = "RLLLLRRRLR"
* 输出:3
* 解释:s 可以分割为 "RL", "LLLRRR", "LR", 每个子字符串中都包含相同数量的 'L' 和 'R'。
* 示例 3:
* 输入:s = "LLLLRRRR"
* 输出:1
* 解释:s 只能保持原样 "LLLLRRRR".
* 【提示】
* 1 <= s.length <= 1000
* s[i] = 'L' 或 'R'
*/
public class SplitAStringInBalancedStrings {
public int balancedStringSplit(String s) {
int l = 0;
int r = 0;
int result = 0;
char[] chars = s.toCharArray();
for (char a : chars) {
if (a == 'L') {
l++;
}else {
r++;
}
if (l == r){
l=0;r=0;result++;
continue;
}
}
return result;
}
public static void main(String[] args) {
SplitAStringInBalancedStrings strings = new SplitAStringInBalancedStrings();
System.out.println(strings.balancedStringSplit(""));
}
}