Lc43---- 1221. 分割平衡字符串(java版)---(贪心)(字符串)

1.题目描述

在这里插入图片描述

2.知识点和思路

(1)贪心算法的基本思想
选择性质:在每一步中,选择当前最优的选项,不考虑未来的后果。
局部最优解:通过一系列局部最优选择,构建全局最优解。
不可回溯:一旦做出选择,不能回溯来改变之前的选择。
(2)贪心算法的例子
例子 1:找零问题
问题:给定一个金额,求用最少数量的硬币凑出该金额。假设硬币的面值有 1 元、5 元、10 元和 25 元。
贪心算法的思想:每次选择面值最大的硬币。
算法步骤:
选择当前金额下可用的最大面值的硬币。
从总金额中减去该硬币的面值。
重复上述步骤,直到总金额为 0。

import java.util.ArrayList;
import java.util.List;

public class CoinChange {
    public static List<Integer> coinChange(int amount) {
        int[] coins = {25, 10, 5, 1};
        List<Integer> result = new ArrayList<>();

        for (int coin : coins) {
            while (amount >= coin) {
                amount -= coin;
                result.add(coin);
            }
        }

        return result;
    }

    public static void main(String[] args) {
        int amount = 41;
        List<Integer> result = coinChange(amount);
        System.out.println(result); // 预期输出: [25, 10, 5, 1]
    }
}

(3)贪心算法的例子2(太抽象了,暂时理解不了)
例子 2:活动选择问题
问题:给定一组活动,每个活动有开始时间和结束时间,要求选择尽可能多的互不重叠的活动。
贪心算法的思想:每次选择结束时间最早的活动,这样可以确保剩下的时间最大化。
算法步骤:
按活动结束时间排序。
选择第一个活动。
对于每个后续活动,如果其开始时间大于等于上一个选择活动的结束时间,则选择该活动。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ActivitySelection {
    public static List<int[]> activitySelection(int[][] activities) {
        // 按活动结束时间排序
        Arrays.sort(activities, (a, b) -> a[1] - b[1]);
        List<int[]> result = new ArrayList<>();

        int[] lastActivity = activities[0];
        result.add(lastActivity);

        for (int i = 1; i < activities.length; i++) {
            if (activities[i][0] >= lastActivity[1]) {
                lastActivity = activities[i];
                result.add(lastActivity);
            }
        }

        return result;
    }

    public static void main(String[] args) {
        int[][] activities = {
            {1, 4},
            {3, 5},
            {0, 6},
            {5, 7},
            {3, 8},
            {5, 9},
            {6, 10},
            {8, 11},
            {8, 12},
            {2, 13},
            {12, 14}
        };
        List<int[]> result = activitySelection(activities);
        for (int[] activity : result) {
            System.out.println(Arrays.toString(activity));
        }
        // 预期输出: [[1, 4], [5, 7], [8, 11], [12, 14]]
    }
}

(4)返回可以通过分割得到的平衡字符串的 最大数量 。
我的思路是要返回平衡字符串的最大数量,说明分割的子字符串要足够的小,且保证字符串的两种字符的数量是想等的。

(5)字符串分割是处理和解析字符串的常见操作。
例子1:使用 split 方法
split 方法使用正则表达式将字符串分割成子字符串数组。

public class SplitExample {
    public static void main(String[] args) {
        String str = "apple,banana,cherry";
        String[] fruits = str.split(",");
        
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
        // 预期输出:
        // apple
        // banana
        // cherry
    }
}

例子2:知道分割的位置,可以使用 substring 方法手动分割字符串。

public class SubstringExample {
    public static void main(String[] args) {
        String str = "apple-banana-cherry";
        int firstDash = str.indexOf("-");
        int secondDash = str.indexOf("-", firstDash + 1);
        
        String firstPart = str.substring(0, firstDash);
        String secondPart = str.substring(firstDash + 1, secondDash);
        String thirdPart = str.substring(secondDash + 1);
        
        System.out.println(firstPart);
        System.out.println(secondPart);
        System.out.println(thirdPart);
        // 预期输出:
        // apple
        // banana
        // cherry
    }
}

补充1:substring 方法在 Java 中用于从字符串中提取子字符串。它有两种主要的使用方式:
1)substring(int beginIndex):返回从指定的起始索引(包含)开始到字符串末尾的子字符串。

public class SubstringExample1 {
    public static void main(String[] args) {
        String str = "apple-banana-cherry";
        
        // 从索引 6 开始到字符串末尾的子字符串
        String subStr1 = str.substring(6);
        System.out.println(subStr1); // 预期输出: banana-cherry
    }
}

2)substring(int beginIndex, int endIndex):返回从指定的起始索引(包含)到结束索引(不包含)之间的子字符串。

public class SubstringExample2 {
    public static void main(String[] args) {
        String str = "apple-banana-cherry";
        
        // 从索引 6 开始到索引 12 (不包含) 的子字符串
        String subStr2 = str.substring(6, 12);
        System.out.println(subStr2); // 预期输出: banana
    }
}

补充2:str.indexOf(“-”) 方法在 Java 中用于查找字符串中第一次出现指定子字符串或字符的位置。它返回子字符串或字符在字符串中的索引(位置),如果找不到则返回 -1。

public class IndexOfExample {
    public static void main(String[] args) {
        String str = "apple-banana-cherry";
        
        // 找到第一个 '-' 的位置
        int firstDash = str.indexOf("-");
        System.out.println("The first '-' is at index: " + firstDash); // 预期输出: 5
        
        // 找到第二个 '-' 的位置,从第一个 '-' 之后开始搜索
        int secondDash = str.indexOf("-", firstDash + 1);
        System.out.println("The second '-' is at index: " + secondDash); // 预期输出: 12
    }
}

补充3:结合 indexOf 和 substring 使用

public class CombinedExample {
    public static void main(String[] args) {
        String str = "apple-banana-cherry";
        
        // 找到第一个 '-' 的位置
        int firstDash = str.indexOf("-");
        
        // 找到第二个 '-' 的位置,从第一个 '-' 之后开始搜索
        int secondDash = str.indexOf("-", firstDash + 1);
        
        // 提取第一个 '-' 之前的子字符串
        String firstPart = str.substring(0, firstDash);
        System.out.println("First part: " + firstPart); // 预期输出: apple
        
        // 提取第一个 '-' 和第二个 '-' 之间的子字符串
        String secondPart = str.substring(firstDash + 1, secondDash);
        System.out.println("Second part: " + secondPart); // 预期输出: banana
        
        // 提取第二个 '-' 之后的子字符串
        String thirdPart = str.substring(secondDash + 1);
        System.out.println("Third part: " + thirdPart); // 预期输出: cherry
    }
}

补充4:实现括号平衡检查

import java.util.Stack;

public class BalancedParentheses {
    public static boolean isBalanced(String s) {
        Stack<Character> stack = new Stack<>();
        
        for (char c : s.toCharArray()) {
            if (c == '(' || c == '{' || c == '[') {
                stack.push(c);
            } else if (c == ')' || c == '}' || c == ']') {
                if (stack.isEmpty()) {
                    return false;
                }
                char top = stack.pop();
                if (!isMatchingPair(top, c)) {
                    return false;
                }
            }
        }
        
        return stack.isEmpty();
    }
    
    private static boolean isMatchingPair(char left, char right) {
        return (left == '(' && right == ')') ||
               (left == '{' && right == '}') ||
               (left == '[' && right == ']');
    }
    
    public static void main(String[] args) {
        String test1 = "{[()]}";
        String test2 = "{[(])}";
        String test3 = "{{[[(())]]}}";
        
        System.out.println(isBalanced(test1)); // 预期输出: true
        System.out.println(isBalanced(test2)); // 预期输出: false
        System.out.println(isBalanced(test3)); // 预期输出: true
    }
}

3.代码实现

先弄L,R计数器,还有一个平衡计数器。
在for循环里面(首先要满足将字符串变成字符数组,也就是s.toCharArrat())
对L、R字符进行计数,当cntL==cntR的时候,平衡字符串计数+1,cntL和cntR重新置0.

class Solution {
    public int balancedStringSplit(String s) {

         int cntL=0;
         int cntR=0;
         int BalanceCnt=0;

         for(char c:s.toCharArray())
         {
            if(c=='R')
            {
                cntR++;
            }
            else if(c=='L')
            {
                cntL++;
            }

               if(cntR==cntL)
         {
            BalanceCnt++;
            cntR=0;
            cntL=0;
         }
       
         }
        
         return BalanceCnt;

    }
}
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值