LeetCode 题解工作台

分割字符串的最大得分

给你一个由若干 0 和 1 组成的字符串 s ,请你计算并返回将该字符串分割成两个 非空 子字符串(即 左 子字符串和 右 子字符串)所能获得的最大得分。 「分割字符串的得分」为 左 子字符串中 0 的数量加上 右 子字符串中 1 的数量。 示例 1: 输入: s = "011101" 输出: 5 …

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 前缀和

bolt

答案摘要

我们用两个变量 和 分别记录左子字符串中 的数量和右子字符串中 的数量。初始时 $l = 0$,而 则等于字符串 中 的数量。 遍历字符串 的前 $n - 1$ 个字符,对于每一个位置 ,如果 $s[i] = 0$,则 自增 ,否则 自减 。然后我们更新答案为 $l + r$ 的最大值。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 前缀和 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个由若干 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

 

提示:

  • 2 <= s.length <= 500
  • 字符串 s 仅由字符 '0''1' 组成。
lightbulb

解题思路

方法一:计数

我们用两个变量 llrr 分别记录左子字符串中 00 的数量和右子字符串中 11 的数量。初始时 l=0l = 0,而 rr 则等于字符串 ss11 的数量。

遍历字符串 ss 的前 n1n - 1 个字符,对于每一个位置 ii,如果 s[i]=0s[i] = 0,则 ll 自增 11,否则 rr 自减 11。然后我们更新答案为 l+rl + r 的最大值。

时间复杂度 O(n)O(n),其中 nn 为字符串 ss 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
class Solution:
    def maxScore(self, s: str) -> int:
        l, r = 0, s.count("1")
        ans = 0
        for x in s[:-1]:
            l += int(x) ^ 1
            r -= int(x)
            ans = max(ans, l + r)
        return ans
speed

复杂度分析

指标
时间O(n)
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Do you consider all split points including minimal left and right substrings?

  • question_mark

    Have you optimized the calculation of ones on the right using prefix sums?

  • question_mark

    Can you explain why recomputing counts at every split is inefficient?

warning

常见陷阱

外企场景
  • error

    Forgetting to handle both substrings as non-empty when iterating split points.

  • error

    Recalculating right-side ones for each split instead of using a prefix sum.

  • error

    Miscounting zeros in the left substring when updating the score.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Compute the minimum score after splitting a string with the same zero-left, one-right rule.

  • arrow_right_alt

    Given a ternary string '0', '1', '2', maximize zeros-left plus ones-right plus twos-right.

  • arrow_right_alt

    Allow splitting into more than two substrings and compute the maximum combined score.

help

常见问题

外企场景

分割字符串的最大得分题解:前缀和 | LeetCode #1422 简单