Split a String in Balanced Strings

Balanced strings are those who have 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 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'.

思路:扫描,遇见L count+1,遇见Rcount-1,只要count == 0的时候,发现一个balance string

class Solution {
    public int balancedStringSplit(String s) {
        if(s == null || s.length() == 0) {
            return 0;
        }
        int count = 0;
        int result = 0;
        for(int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if(c == 'L') {
                count++;
            } else {
                count--;
            }
            if(count == 0) {
                result++;
            }
        }
        return result;
    }
}
发布了663 篇原创文章 · 获赞 13 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/u013325815/article/details/104752050