1422. Maximum score after splitting a string
Given a strings
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.
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
java
class Solution {
public int maxScore(String s) {
int n = s.length();
List<Integer> scores = new ArrayList<>();
for (int i = 1; i<n; i++){
String left = s.substring(0,i);
String right = s.substring(i);
int score = countOccurences(left,'0') + countOccurences(right,'1');
scores.add(score);
}
return Collections.max(scores);
}
private int countOccurences(String str, char ch){
int count = 0;
for (int i = 0; i<str.length(); i++){
if (str.charAt(i) == ch){
count++;
}
}
return count;
}
}
python
class Solution:
def maxScore(self, s: str) -> int:
n = len(s)
hb = [0 for _ in range(n)]
for i in range(1,n):
left,right = s[:i], s[i:]
hb[i] = left.count("0") + right.count("1")
return max(hb)
javascript
var maxScore = function(s) {
const n = s.length;
let maxScore = 0;
for (let i = 1; i<n;i++){
const [left,right] = [s.substring(0, i), s.substring(i)];
const countLeftZeros = left.split("0").length - 1;
const countRightOnes = right.split("1").length - 1;
const currentScore = countLeftZeros + countRightOnes;
maxScore = Math.max(currentScore, maxScore);
}
return maxScore;
};
All three solutions have same logical flow. But as you can see, the length of the code of python code is absolutely shorter than the other two. And also much simple. The way to count some string in a string is just count
in python. But in javascript it is string.split("something").length - 1
something like this. And in java we had to make a private function to get function.