给你一个由若干 0 和 1 组成的字符串 s ,请你计算并返回将该字符串分割成两个 非空 子字符串(即 左 子字符串和 右 子字符串)所能获得的最大得分。
「分割字符串的得分」为 左 子字符串中 0 的数量加上 右 子字符串中 1 的数量。
来源:力扣(LeetCode)
解答一:枚举
遍历每种分割情况然后分别计算得分
class Solution {
public:
int countNumber(string str,char n){
int c = 0;
for(char ch:str){
if(ch == n) c++;
}
return c;
}
int maxScore(string s) {
int len = size(s);
int res = 0;
for(int i = 1; i < len; i++){
int tmp =countNumber(s.substr(0,i),'0') + countNumber(s.substr(i,len-i), '1');
res = max(tmp, res);
}
return res;
}
};
解答二:根据分割点的移动更新得分,最终取最大值
class Solution {
public:
int maxScore(string s) {
int score = 0;
if(s[0]=='0') score++;
for(int i = 1; i < size(s); i++){
if(s[i] == '1') score++;
}
int ans = score;
for(int i = 1; i < size(s)-1; i++){
if(s[i] == '0'){
score++;
}else{
score--;
}
ans = max(ans, score);
}
return ans;
}
};