1221. Split a String in Balanced

2019-10-22  本文已影响0人  守住这块热土

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. 题目关键词


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;
}
// 题目已要求给的是一个平衡字符串
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;
}
上一篇下一篇

猜你喜欢

热点阅读