题解 | #牛牛的牧场#
牛牛的牧场
https://www.nowcoder.com/practice/549f2fecfa554df7b47edca5c91313ce
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return int整型
*/
int countValidWays(string s) {
// write code here
//初始化ans,0的数量,1的数量,01的数量,10的数量
int ans = 0, f0 = 0, f1 = 0, f01 = 0, f10 = 0;
for(auto c : s){
if(c == '0'){
//当前可取区域为010,所以加上前两个区域01的个数
ans += f01;
f0++;
f10 += f1;
}else{
//当前可取区域为101,所以加上前两个区域10的个数
ans += f10;
f1++;
f01 += f0;
}
}
return ans;
}
};

查看4道真题和解析