Given a string
The score after splitting a string is the number of zeros in the left substring plus the number of ones in the right substring.
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
Approach
Java
public class MaxScoreAfterSplittingString {public static void main(String[] args) {String s = "011101";System.out.println(maxScore(s));}static int maxScore(String s) {String str1, str2;int n = s.length();int i = 0, max1 = Integer.MIN_VALUE, res;while (i < n - 1) {str1 = s.substring(0, i + 1);str2 = s.substring(i + 1, n);res = zeros(str1) + ones(str2);if (res > max1)max1 = res;i++;}return max1;}static int zeros(String s) {int cnt = 0;for (int i = 0; i < s.length(); i++)if (s.charAt(i) == '0')cnt++;return cnt;}static int ones(String s) {int cnt = 0;for (int i = 0; i < s.length(); i++)if (s.charAt(i) == '1')cnt++;return cnt;}}
C++
#include <bits/stdc++.h>using namespace std;int zeros(string s){int cnt = 0;for (int i = 0; i < s.size(); i++)if (s[i] == '0')cnt++;return cnt;}int ones(string s){int cnt = 0;for (int i = 0; i < s.size(); i++)if (s[i] == '1')cnt++;return cnt;}int maxScore(string s){string str1, str2;int n = s.size();int i = 0, max1 = INT_MIN, res;while (i < n - 1){str1 = s.substr(0, i + 1);str2 = s.substr(i + 1, n);res = zeros(str1) + ones(str2);if (res > max1)max1 = res;i++;}return max1;}int main(){string s = "011101";cout << maxScore(s);return 0;}
No comments:
Post a Comment