题目是LeetCode第186场周赛的第一题,链接:分割字符串的最大得分。具体描述为:给你一个由若干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
示例2:
输入:s = "00111"
输出:5
解释:当 左子字符串 = "00" 且 右子字符串 = "111" 时,我们得到最大得分 = 2 + 3 = 5
示例3:
输入:s = "1111"
输出:3
题目很简单,直接统计每个分隔位置上左边的0
和右边的1
的数目,则此位置的得分就是这两者之和。统计的话可以线性遍历得到,统计数目这里先用一个数组保存,则时间复杂度为
O
(
n
)
O(n)
O(n),空间复杂度为
O
(
n
)
O(n)
O(n)。
JAVA版代码如下:
class Solution {
public int maxScore(String s) {
char[] chars = s.toCharArray();
int N = chars.length;
int[] count0 = new int[N - 1];
int[] count1 = new int[N - 1];
for (int i = 0, count = 0; i < N - 1; ++i) {
if (chars[i] == '0') {
count0[i] = ++count;
}
else {
count0[i] = count;
}
}
for (int i = N - 2, count = 0; i >= 0; --i) {
if (chars[i + 1] == '1') {
count1[i] = ++count;
}
else {
count1[i] = count;
}
}
int result = 0;
for (int i = 0; i < N - 1; ++i) {
result = Math.max(result, count0[i] + count1[i]);
}
return result;
}
}
提交结果如下:
然后可以进一步减少空间复杂度,首先从左往右遍历,记录左边0
的个数,作为当前的得分,然后再从右往左遍历,遇到1
说明右边1
的个数增加了,但左边0
的个数不变,所以得分+1;在非最后位置遇到0
的话说明右边1
的个数不变,但左边0
的个数减少,所以得分-1。则时间复杂度仍为
O
(
n
)
O(n)
O(n),空间复杂度减为
O
(
1
)
O(1)
O(1)。
JAVA版代码如下:
class Solution {
public int maxScore(String s) {
char[] chars = s.toCharArray();
int N = chars.length;
int count = 0, result = 0;
for (int i = 0; i < N - 1; ++i) {
// 先统计左边0的个数
if (chars[i] == '0') {
++count;
}
}
for (int i = N - 1; i > 0; --i) {
// 再从右往左遍历,遇到1说明右边1的个数增加了,但左边0的个数不变,所以得分+1
if (chars[i] == '1') {
++count;
}
// 在非最后位置遇到0的话说明右边1的个数不变,但左边0的个数减少,所以得分-1
else if (i < N - 1) {
--count;
}
result = Math.max(result, count);
}
return result;
}
}
提交结果如下:
Python版代码如下:
class Solution:
def maxScore(self, s: str) -> int:
N = len(s)
count, result = 0, 0
for i in range(N - 1):
if s[i] == '0':
count += 1
for i in range(N - 1, 0, -1):
if s[i] == '1':
count += 1
elif i < N - 1:
count -= 1
result = max(result, count)
return result
提交结果如下: