• 【字符串】分割字符串的最大得分


    题目描述

    给你一个由若干 0 和 1 组成的字符串 s ,请你计算并返回将该字符串分割成两个 非空 子字符串(即左 子字符串和 右 子字符串)所能获得的最大得分。

    「分割字符串的得分」为 左 子字符串中 0 的数量加上 右 子字符串中 1 的数量。

    示例 1:

    输入:s = "011101"
    输出:5 
    解释:
    将字符串 s 划分为两个非空子字符串的可行方案有:
    左子字符串 = "0" 且 右子字符串 = "11101",得分 = 1 + 4 = 5 
    左子字符串 = "01" 且 右子字符串 = "1101",得分 = 1 + 3 = 4 
    左子字符串 = "011" 且 右子字符串 = "101",得分 = 1 + 2 = 3 
    左子字符串 = "0111" 且 右子字符串 = "01",得分 = 1 + 1 = 2 
    左子字符串 = "01110" 且 右子字符串 = "1",得分 = 2 + 1 = 3

    解题思路 

    这道题是一道简单题目,主要用于统计字符:'0' 和 '1' 出现的次数,思路如下:

    1. 准备一个数组,记录'0' 和 '1'的出现次数;
    2. 获取1出现总共次数:total1,计算公式:0出现次数+(total1-1出现次数)


    代码实现

    1. class Solution {
    2. public int maxScore(String s) {
    3. int[][] array = new int[s.length()][2];
    4. if (s.charAt(0) == '0') {
    5. array[0][0] = 1;
    6. } else {
    7. array[0][1] = 1;
    8. }
    9. for (int i = 1; i < s.length(); i++) {
    10. if (s.charAt(i) == '0') {
    11. array[i][0] += array[i - 1][0] + 1;
    12. array[i][1] = array[i - 1][1];
    13. } else {
    14. array[i][0] = array[i - 1][0];
    15. array[i][1] += array[i - 1][1] + 1;
    16. }
    17. }
    18. int total1 = array[array.length - 1][1];
    19. int max = array[0][0] + total1 - array[0][1];
    20. for (int i = 1; i < array.length - 1; i++) {
    21. System.out.println(array[i][0] + total1 - array[i][1]);
    22. max = Math.max(max, array[i][0] + total1 - array[i][1]);
    23. }
    24. return max;
    25. }
    26. public static void main(String[] args) {
    27. Solution solution = new Solution();
    28. System.out.println(solution.maxScore("011101"));
    29. }
    30. }

    代码优化,我优先减少计算次数,计算公式如下:array[i] + total1 - (i+1 - array[i])

    1. class Solution2 {
    2. public int maxScore(String s) {
    3. int[] array = new int[s.length()];
    4. int total1 = 0;
    5. if (s.charAt(0) == '0') {
    6. array[0] = 1;
    7. } else {
    8. total1 = 1;
    9. }
    10. for (int i = 1; i < s.length(); i++) {
    11. if (s.charAt(i) == '0') {
    12. array[i] += array[i - 1] + 1;
    13. } else {
    14. array[i] = array[i - 1];
    15. total1++;
    16. }
    17. }
    18. int max = array[0] + total1 - (1 - array[0]);
    19. for (int i = 1; i < array.length - 1; i++) {
    20. max = Math.max(max, array[i] + total1 - (i+1 - array[i]));
    21. }
    22. return max;
    23. }
    24. public static void main(String[] args) {
    25. Solution2 solution = new Solution2();
    26. System.out.println(solution.maxScore("011101"));
    27. }
    28. }

    总结 

    这是一套简单题,在耗时方面我的解法也不是最快的,欢迎大家提供更快、更简洁的解法。

     

     

     

  • 相关阅读:
    【linux系统】如何在服务器上安装Anaconda
    SpringBoot3安全管理
    Wordpress 生手遇到一堆问题,反应巨慢,提速插件又是一堆错误
    Spring Boot 到底是单线程还是多线程
    sed编辑器
    Spring Cloud Eureka:服务注册与发现
    Linux安装Redis
    【JavaScript】如何获取指定范围内的随机数
    Ultralytics(YoloV8)开发环境配置,训练,模型转换,部署全流程测试记录
    RDD的执行原理
  • 原文地址:https://blog.csdn.net/weiliuhong1/article/details/126330090