LeetCode Maximum Score After Splitting a String

1422. Maximum Score After Splitting a String

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.

给定一个仅包含0/1的字符串,要求把它分成两半,使得左边的0的数目加上右边的1的数目的和最大。

简单题,提前算好左边的0的数目的累加和,和右边的1的数目的累加和。完整代码如下:

class Solution {
public:
	int maxScore(string s) {
		int n = s.size();
		vector<int> zeros(n, 0), ones(n, 0);
		for (int i = 0; i < n - 1; ++i) {
			if (i == 0)zeros[i] = (s[i] == '0' ? 1 : 0);
			else zeros[i] = zeros[i - 1] + (s[i] == '0' ? 1 : 0);

			int j = n - i - 1;
			if (j == n - 1)ones[j] = (s[j] == '1' ? 1 : 0);
			else ones[j] = ones[j + 1] + (s[j] == '1' ? 1 : 0);
		}
		int ans = 0;
		for (int i = 0; i < n - 1; ++i) {
			ans = max(ans, zeros[i] + ones[i + 1]);
		}
		return ans;
	}
};

本代码提交AC,用时4MS。

Leave a Reply

Your email address will not be published. Required fields are marked *