[leetcode] 1422. Maximum Score After Splitting a String

网友投稿 634 2022-10-20

[leetcode] 1422. Maximum Score After Splitting a String

[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: 5Explanation: 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 <= 500The 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​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:[leetcode] 1419. Minimum Number of Frogs Croaking
下一篇:Hopen- Golang web极速开发框架
相关文章

 发表评论

暂时没有评论,来抢沙发吧~