Split balanced string [JavaScript]

Split balanced character string
In a "balanced character string", the number of'L' and'R' characters are the same.

Given a balanced string s, please split it into as many balanced strings as possible.

Returns the maximum number of balanced strings that can be obtained by splitting.

Example 1:

Input: s = "RLRRLLRLRL"
Output: 4
Explanation: s can be divided into "RL", "RRLL", "RL", "RL", and each substring contains the same number of'L' and'R'.
Example 2:

Input: s = "RLLLLRRRLR"
Output: 3
Explanation: s can be divided into "RL", "LLLRRR", "LR", and each substring contains the same number of'L' and'R'.
Example 3:

Input: s = "LLLLRRRR"
Output: 1
Explanation: s can only remain as it is "LLLLRRRR".

Tips:
1 <= s.length <= 1000
s[i] ='L' or'R '
Source of the question: Likou 1221
Method 1 is a
simple question, just go through it directly, set variables to record the number of occurrences of R and the occurrence of L respectively Times, if two times are equal, it is a balanced string.

/**
 * @param {string} s
 * @return {number}
 */
var balancedStringSplit = function(s) {
    
    
    if (s.length === 0) return 0;
    let char;
    let numOfR = 0,
        numOfL = 0;
    let max = 0;
    for (let i = 0; i < s.length; i++) {
    
    
        char = s[i];
        if (char === "R") {
    
    
            numOfR++
        } else {
    
    
            numOfL++;
        }
        if (numOfR === numOfL) {
    
    
            max++;
            numOfR = 0;
            numOfL = 0
        }
    }
    return max;
};

Method two
Method two is the optimization of method one. Only one variable is set to determine whether there is a balanced string.

/**
 * @param {string} s
 * @return {number}
 */
var balancedStringSplit = function(s) {
    
    
    if (s.length === 0) return 0;
    let char;
    let num = 0;
    let max = 0;
    for (let i = 0; i < s.length; i++) {
    
    
        char = s[i];
        if (char === "R") {
    
    
            num++
        } else {
    
    
            num--;
        }
        if (num === 0) {
    
    
            max++;
        }
    }
    return max;
};

Guess you like

Origin blog.csdn.net/weixin_42345596/article/details/104946031