題目描述:
一個括號序列是指一個由'(', ')', '[', ']'四種字符組成的字符串。
一個只包含數字,加號'+',和上述四種括號的合法算數表達式,去掉數字和加號之後得到的括號序列成爲合法的括號序列。我們定義空串也是合法的括號序列。
例如(1) + [2], ([3]), 4 + [5]相應的括號序列 "()[]", "([])", "[]"都是合法的括號序列。而(6 + 7], [8 + ((9對應的"(]", "[(("則是非法的。
字符串s0s1s2⋯s|s|−1的子串s[l,r](0≤ l≤r<|s|)是指slsl+1⋯sr。
現在給定一個括號序列,請找出其中的一個子串,使得這個子串是合法的括號序列,且包含的'['數量最多。
輸入:
一個括號序列s。1≤|s|≤5×100000
輸出:
第一行,答案要求的子串中包含'['的數量。
如果答案是0,輸出到此爲止,否則:
第二行,兩個整數l, r。表示子串第一個字符的位置和最後一個字符的位置。
如果有多個滿足條件的字符串,請輸出使得子串長度最大的答案。如果長度最大的仍有多個,請輸出r最大的。
樣例:
input:
([])
output:
1
0 3
用棧的思想。先入後出。用一個數組來模擬棧。然後就是一些細節的處理。
#pragma comment(linker, "/STACK:102400000,102400000")
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define maxn 500005
char ch[maxn];
typedef struct {
int pos;
char cc;
}NODE;
NODE stack[maxn];
typedef struct {
int left, right, leng;
}ANS;
ANS ans;
int top=0;
int l, r, le;
void push(int k, char c)
{
top++;
stack[top].pos = k;
stack[top].cc = c;
}
void pull(int k,char c)
{
if (top > 0)
{
if (stack[top].cc != c)
{
top = 0;
l = maxn;r = 0;le = 0;
}
else {
if (stack[top].pos < l)
l = stack[top].pos;
r = k;
if (c == '[')
le++;
top--;
if( (le > ans.leng || (le == ans.leng&&r - l > ans.right - ans.left))&&stack[top].pos<=l)
{
ans.left = l;ans.leng = le; ans.right = r;
}
}
}
else {
top = 0;
l = maxn;r = 0;le = 0;
}
}
void pull1(int k,char c)
{
if (top > 0)
{
if (stack[top].cc != c)
{
top = 0;
l = 0;r = 0;le = 0;
}
else {
if (stack[top].pos > r)
r = stack[top].pos;
l = k;
if (c == ']')
le++;
top--;
if( (le > ans.leng || (le == ans.leng&&r - l > ans.right - ans.left))&&stack[top].pos>=r&&stack[top].pos>=r)
{
ans.left = l;ans.leng = le; ans.right = r;
}
}
}
else {
top = 0;
l = maxn;r = 0;le = 0;
}
}
int main()
{
//freopen("E:in.txt","r",stdin);
//freopen("E:outt.txt","w",stdout);
int i;
int len;
while( scanf("%s", ch)!=EOF){
len = strlen(ch);
ans.left = maxn;ans.right = 0;ans.leng = 0;
top=0;
l=maxn;r=0;le=0;
stack[0].pos=maxn;
for (i = len-1;i >= 0;i--)
{
if (ch[i] == ']'||ch[i]==')')
{
push(i,ch[i]);
}
if (ch[i] == '[')
{
pull1(i,']');
}
if (ch[i] == '(')
pull1(i, ')');
}
l=maxn;r=0;le=0;
top=0;stack[0].pos=0;
for (i = 0;i < len;i++)
{
if (ch[i] == '['||ch[i]=='(')
{
push(i,ch[i]);
}
if (ch[i] == ']')
{
pull(i,'[');
}
if (ch[i] == ')')
pull(i, '(');
}
printf("%d\n", ans.leng);
if (ans.leng)
printf("%d %d\n", ans.left, ans.right);
}
}