📘

LeetCode #1221 Split a String in Balanced Strings

2025/02/26に公開

問題概要

入力値:s (Balanced strings)
出力値:the maximum number of balanced strings (int)
問題のリンク

入力例

Input: s = "RLRRLLRLRL"
Output: 4

解答例1

計算量:O(n)
Python

class Solution(object):
    def balancedStringSplit(self, s):
        """
        :type s: str
        :rtype: int
        """
        current_value = 0
        result = 0
        for c in s:
            if c == "R":
                current_value += 1
            else:
                current_value -= 1
            if current_value == 0:
                result += 1
        return result

Runtime: 0ms
Beats: 100%

C++

class Solution {
public:
    int balancedStringSplit(string s) {
        int current_val = 0;
        int result = 0;
        for (auto c : s) {
            if (c == 'R') {
                current_val += 1;
            } else {
                current_val -= 1;
            }
            if (current_val == 0) {
                result += 1;
            }
        }
        return result;
    }
};

Runtime: 0ms
Beats: 100%

Discussion