美文网首页
1221. Split a String in Balanced

1221. Split a String in Balanced

作者: 守住这块热土 | 来源:发表于2019-10-22 18:06 被阅读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. 题目关键词

    • 难度等级: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;
    }
    

    相关文章

      网友评论

          本文标题:1221. Split a String in Balanced

          本文链接:https://www.haomeiwen.com/subject/fkyqvctx.html