洛谷11月月賽 III Div.2 T1 基礎字符串練習題

題目大意:

給定長度非0的非空01串S。

求S的非空連續子串T中’0’的個數- '1’的個數的最大值。

解題思路:

O(n)O(n)掃一遍即可

Accepted code:Accepted\ code:

#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;

int sum, ans;
char s[100005];

int main() {
	scanf("%s", s + 1);
	int len = strlen(s + 1);
	for (int i = 1; i <= len; ++i) {
		sum += (s[i] == '0') ? 1 : -1;
		ans = max(ans, sum = max(sum, 0));
	}
	return !printf("%d", ans == 0 ? -1 : ans);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章