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 le
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