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;
}
}
1221. 分割平衡字符串
最新推荐文章于 2022-06-24 16:33:15 发布