给你一个仅由 0
和 1
组成的二进制字符串 s
。
如果子字符串中 所有的 0
都在 1
之前 且其中 0
的数量等于 1
的数量,则认为 s
的这个子字符串是平衡子字符串。请注意,空子字符串也视作平衡子字符串。
返回 s
中最长的平衡子字符串长度。
子字符串是字符串中的一个连续字符序列。
解题思路:
数字只有0和1的变化,在0?1判断的基础上,需要把字符串进行切片,找到切片的中止条件,就是1后边接着0。
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
int findTheLongestBalancedSubstring(string s) {
int ZeroCounter = 0;
int OneCounter = 0;
int length = 0;
for (int i = 0; i < s.length(); i++){
if (s[i] == '1' && s[i + 1] == '0'){
OneCounter++;
length = max(length, 2*min(ZeroCounter, OneCounter));
ZeroCounter = 0;
OneCounter = 0;
}
else if (s[i] == '0'){
ZeroCounter++;
}
else if (s[i] == '1'){
OneCounter++;
length = max(length, 2*min(ZeroCounter, OneCounter));
}
}
return length;
}
};
int main() {
string s = "010";
Solution solution;
std::cout << solution.findTheLongestBalancedSubstring(s) << std::endl;
// std::cout << "Hello, World!" << std::endl;
return 0;
}