[LeetCode] 1221. Split a String in Balanced Strings 分割平衡字符串



Balanced strings are those that have an equal quantity of 'L' and 'R' characters.

Given a balanced string s, split it in the maximum amount of balanced strings.

Return the maximum amount of split 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".

Example 4:

Input: s = "RLRRRLLRLL"
Output: 2
Explanation: s can be split into "RL", "RRRLLRLL", since each substring contains an equal number of 'L' and 'R'

Constraints:

  • 1 <= s.length <= 1000
  • s[i] is either 'L' or 'R'.
  • s is a balanced string.

這道題給了一個只有L和R兩個字符的字符串,並且定義了一種平衡字符串,即L和R的個數相同,現在問最多能將字符串分為多少個這樣的平衡字符串。博主看到這題以后第一反應就覺得這是一道驗證合法括號個數的題目,就像之前的那道 Valid Parentheses,這里的L就可以看作是左括號,R可以看作是右括號,其實這道題比驗證合法括號更簡單一些,因為合法括號不僅僅需要左右括號個數相同,而且任何時候右括號的個數不能多於左括號,而這道題並沒有這個限制。這里只需要一個 cnt 變量來記錄L的個數,遇到L則 cnt 自增1,遇到R則 cnt 自減1。每次檢測一下,若某個狀態 cnt 為0了,則說明此時L和R個數相等了,結果 res 自增1即可,參見代碼如下:


class Solution {
public:
    int balancedStringSplit(string s) {
        int res = 0, cnt = 0;
        for (char c : s) {
            (c == 'L') ? ++cnt : --cnt;
            if (cnt == 0) ++res;
        }
        return res;
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1221


類似題目:

Valid Parentheses


參考資料:

https://leetcode.com/problems/split-a-string-in-balanced-strings/

https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/403836/C%2B%2BJavaPython-Easy-Solution


LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM