Title 1221, the balance split the string

I, entitled

In a "balanced string", the number of 'L' and 'R' character is the same.
Given a balanced string s, you divide it into as many balance strings.
Returns the maximum number of equilibrium can be obtained by a division of the string. 1
Here Insert Picture Description

Second, the idea

Precautions: dividing the substring must balance the string are all

To give you a balanced string, and then to split it directly count, one by one number, once they reach the same position as the number two on the interception once, and then continue, there is no 0, 1 is the worst.

Third, the code

public class T1221 {

    public static void main(String[] args) {
    
        System.out.println( balancedStringSplit("RLRRLLRLRL") );    //4
        System.out.println( balancedStringSplit("RLLLLRRRLR") );    //3
        System.out.println( balancedStringSplit("LLLLRRRR") );    //1
        System.out.println( balancedStringSplit("RLRRRLLRLL") );    //2
    }

    public static int balancedStringSplit(String s) {

        int  i = 0, j = 0, output = 0;
        for ( int count = 0; count < s.length(); count ++ ){
            if ( i == j ){
                i = 0;
                j = 0;
                output++;
            }

            if (s.charAt(count) == 'R' )
                i++;
            else
                j++;
        }

        return output;
    }
}

  1. Source: stay button (LeetCode)
    link: https: //leetcode-cn.com/problems/split-a-string-in-balanced-strings
    copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source. ↩︎

Published 24 original articles · won praise 0 · Views 107

Guess you like

Origin blog.csdn.net/weixin_45980031/article/details/103466343