1. 题目链接:
https://leetcode.com/problems/split-a-string-in-balanced-strings/
Balanced strings are those who have equal quantity of 'L' and 'R' characters.
Given a balanced string split it in the maximum amount of balanced strings.
Return the maximum amount of splitted balanced strings.
Example 1:
Input: s = "RLRRLLRLRL"
Output: 4
Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'.
Example 2:
Input: s = "RLLLLRRRLR"
Output: 3
Explanation: s can be split into "RL", "LLLRRR", "LR", each substring contains same number of 'L' and 'R'.
Example 3:
Input: s = "LLLLRRRR"
Output: 1
Explanation: s can be split into "LLLLRRRR".
Constraints:=
1 <= s.length <= 1000
s[i] = 'L' or 'R'
2. 题目关键词
- 难度等级:easy
- 关键词:
- 语言: C
3. 解题思路
- 第一种:使用两个计数器
遍历原字符串,找到字符'L'---> LNum++; 'R'---> Rnum++;
如果LNum == Rnum; balanceNum++,并且将LNum 和 Rnum置为0。
// 题目已要求给的是一个平衡字符串
int balancedStringSplit(char * s){
int RNum = 0;
int LNum = 0;
int balanceNum = 0;
for (int i = 0; i < strlen(s); i++) {
if (s[i] == 'L') {
RNum++;
} else if (s[i] == 'R') {
LNum++;
}
if ((RNum == LNum) && RNum != 0) {
balanceNum++;
}
}
return balanceNum;
}
- 思路2:使用一个计数器
遍历字符串时,遇到R,num++;遇到L时,num--; if num == 0, balanceNum++;
// 题目已要求给的是一个平衡字符串
int balancedStringSplit(char * s){
int num = 0;
int balanceNum = 0;
for (int i = 0; i < strlen(s); i++) {
if (s[i] == 'L') {
num++;
} else if (s[i] == 'R') {
num--;
}
if (num == 0) {
balanceNum++;
}
}
return balanceNum;
}
网友评论