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

题目描述

给你一个由若干 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出现次数)


代码实现


class Solution {
    public int maxScore(String s) {
        int[][] array = new int[s.length()][2];

        if (s.charAt(0) == '0') {
            array[0][0] = 1;
        } else {
            array[0][1] = 1;
        }
        for (int i = 1; i < s.length(); i++) {
            if (s.charAt(i) == '0') {
                array[i][0] += array[i - 1][0] + 1;
                array[i][1] = array[i - 1][1];
            } else {
                array[i][0] = array[i - 1][0];
                array[i][1] += array[i - 1][1] + 1;
            }
        }

        int total1 = array[array.length - 1][1];

        int max = array[0][0] + total1 - array[0][1];
        for (int i = 1; i < array.length - 1; i++) {
            System.out.println(array[i][0] + total1 - array[i][1]);
            max = Math.max(max, array[i][0] + total1 - array[i][1]);
        }

        return max;

    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.maxScore("011101"));
    }
}

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


class Solution2 {
    public int maxScore(String s) {
        int[] array = new int[s.length()];
        int total1 = 0;

        if (s.charAt(0) == '0') {
            array[0] = 1;
        } else {
            total1 = 1;
        }
        for (int i = 1; i < s.length(); i++) {
            if (s.charAt(i) == '0') {
                array[i] += array[i - 1] + 1;
            } else {
                array[i] = array[i - 1];
                total1++;
            }
        }

        int max = array[0] + total1 - (1 - array[0]);
        for (int i = 1; i < array.length - 1; i++) {
            max = Math.max(max, array[i] + total1 - (i+1 - array[i]));
        }

        return max;
    }

    public static void main(String[] args) {
        Solution2 solution = new Solution2();
        System.out.println(solution.maxScore("011101"));
    }
}

总结 

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

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值