题目描述
给你一个由若干 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' 出现的次数,思路如下:
- 准备一个数组,记录'0' 和 '1'的出现次数;
- 获取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"));
}
}
总结
这是一套简单题,在耗时方面我的解法也不是最快的,欢迎大家提供更快、更简洁的解法。