[leetcode] 1422. Maximum Score After Splitting a String

Description

Given a string s of zeros and ones, return the maximum score after splitting the string into two non-empty substrings (i.e. left substring and right substring).

The score after splitting a string is the number of zeros in the left substring plus the number of ones in the right substring.

Example 1:

Input: s = "011101"
Output: 5 
Explanation: 
All possible ways of splitting s into two non-empty substrings are:
left = "0" and right = "11101", score = 1 + 4 = 5 
left = "01" and right = "1101", score = 1 + 3 = 4 
left = "011" and right = "101", score = 1 + 2 = 3 
left = "0111" and right = "01", score = 1 + 1 = 2 
left = "01110" and right = "1", score = 2 + 1 = 3

Example 2:

Input: s = "00111"
Output: 5
Explanation: When left = "00" and right = "111", we get the maximum score = 2 + 3 = 5

Example 3:

Input: s = "1111"
Output: 3

Constraints:

  • 2 <= s.length <= 500
  • The string s consists of characters ‘0’ and ‘1’ only.

分析

题目的意思是:给定一个只包含01的字符串,切分成两个字符串后,前一个字符串0的个数和后一个字符串1的个数最大,求最大值。做法很直接,先统计1的个数,然后第二次遍历找切分点,统计遍历国的0的个数,并维护最大值res,注意切分后的两字符串不能为空,所以只能遍历到倒数第二个就停止了。

代码

class Solution:
    def maxScore(self, s: str) -> int:
        cnt1=0
        n=len(s)
        for i in range(n):
            if(s[i]=='1'):
                cnt1+=1
        res=0
        cnt0=0
        for i in range(n-1):
            if(s[i]=='0'):
                cnt0+=1
            else:
                cnt1-=1
            res=max(res,cnt0+cnt1)
        return res

参考文献

[LeetCode] Linear time Python solution with explanation

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值