1221. 分割平衡字符串

package com.leetcode.easy;

import java.util.Stack;

/**
 * 〈1221. 分割平衡字符串〉
 *在一个「平衡字符串」中,'L' 和 'R' 字符的数量是相同的。
 *
 * 给出一个平衡字符串 s,请你将它分割成尽可能多的平衡字符串。
 * 示例 1:
 * 返回可以通过分割得到的平衡字符串的最大数量。
 * 输入:s = "RLRRLLRLRL"
 * 输出:4
 * 解释:s 可以分割为 "RL", "RRLL", "RL", "RL", 每个子字符串中都包含相同数量的 'L' 和 'R'。
 * @author PitterWang
 * @create 2020/5/6
 * @since 1.0.0
 */
public class BalancedStringSplit {


	public static void main(String[] args) {
		System.out.println(balancedStringSplitByNumber("RLRRRLLRLL"));
	}

	/***
	 * 自己的想法~~~有问题
	 * RLRRRLLRLL这样的就有问题了
	 * 学习其他人的妙招
	 * @param s
	 * @return
	 */
	public static int balancedStringSplit(String s) {

		int count = 0;
		while (s.length()>0){
			s = s.substring(test(s),s.length());
			count ++;
		}
		return count;
	}
	public static int test(String s){
		int i = 0;
		char a = s.charAt(i);
		boolean isOk = true;
		while (isOk){
			i++;
			if(s.charAt(i) != a){
				isOk = false;
			}
		}

		return 2 * i;
	}


	/***
	 * 通过栈的方法,如果一样入栈,不一样出栈,如果为空,就说明有
	 * @param s
	 * @return
	 */
	public static int balancedStringSplitByStack(String s) {
		Stack<Character> stack = new Stack<Character>();
		int count = 0;
		for(int i = 0; i < s.length(); i++){
			char c = s.charAt(i);
			if(stack.isEmpty() || c == stack.peek()) {
				stack.push(c);
			}
			else{
				stack.pop();
			}
			if(stack.isEmpty()) {
				count++;
			}
		}
		return count;
	}


	/***
	 * 通过计数法,进行其实思路和栈一样
	 * @param s
	 * @return
	 */
	public static int balancedStringSplitByNumber(String s) {

		int count = 0;
		int cha = 0;
		for(int i = 0; i < s.length(); i++){
			char c = s.charAt(i);


			if(c == 'R') {
				cha++;
			}else{
				cha--;
			}
			if(cha == 0) {
				count++;
			}
		}
		return count;
	}



}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值