第1221题分割字符串

题目链接

思路:既然说是要满足L和R的数量相同,不妨R为正,L为负,只要除了循环开始temp等于零的情况,其他时候temp等于零,都是LR数量相等的状态,此时result自增1,循环遍历结束后,result即为符合条件的次数.

public class 第一二二一_分割平衡字符串 {
    public static int balancedStringSplit(String s) {
        int result =0;
        int temp = 0;
        for (int i = 0; i <s.length() ; i++) {
            if(s.charAt(i) == 'R'){
                temp++;
            }else{
                temp--;
            }
            if(temp == 0){
                result++;
            }
        }
        return result;
    }
    public static void main(String[] args) {
        String s = "LLLLRRRR";
        System.out.println(balancedStringSplit(s));
    }
}
posted @ 2020-08-16 15:38  无法手执玫瑰  阅读(70)  评论(0)    收藏  举报