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. 題目關(guān)鍵詞
- 難度等級:easy
- 關(guān)鍵詞:
- 語言: C
3. 解題思路
- 第一種:使用兩個計數(shù)器
遍歷原字符串,找到字符'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:使用一個計數(shù)器
遍歷字符串時,遇到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;
}