/* 描述:正則問題 考慮一種簡單的正則表達式: 只由 x ( ) | 組成的正則表達式。 小明想求出這個正則表達式能接受的最長字符串的長度。 例如 ((xx|xxx)x|(x|xx))xx 能接受的最長字符串是: xxxxxx,長度是6。 輸入 ---- 一個由x()|組成的正則表達式。輸入長度不超過100,保證合法。 輸出 ---- 這個正則表達式能接受的最長字符串的長度。 例如, 輸入: ((xx|xxx)x|(x|xx))xx 程序應該輸出: 6 */ #include<cstdio> #include<cstring> #include<algorithm> #include<iostream> #include<string> #include<vector> #include<stack> #include<bitset> #include<cstdlib> #include<cmath> #include<set> #include<list> #include<deque> #include<map> #include<queue> using namespace std; const int N=100; char str[N]="((xx|xxx)x|(x|xx))xx"; int i=0; int result=0; int f() { int max=0; int temp=0; while(i<strlen(str)) { if(str[i]=='(') { i++; temp+=f();//還不能確定temp+f()是不是最大,故而不能寫 max+=f(); } else if(str[i]==')') { i++; break;//不能在這里直接寫 return max;因為在返回之前一定還要比較max和temp的大小,從而返回兩者中更大者;而且還要考慮循環的大條件 } else if(str[i]=='|') { i++; if(temp>max) max=temp;//總結這個|字符"之前的"最長x字符串的長度 temp=0; } else//字符為x的情況 { temp++; i++; } } if(temp>max) max=temp; return max; } int main() { //while(scanf("%s",str)!=0&&str!=NULL) { result=f(); cout<<result<<endl; } return 0; }
很難的一題,思考了很久,主要還是對於深度優先算法理解不夠。這道題是誤打誤撞做出來的,並沒有完全理解。不過看過某大佬畫的一張圖,感覺有助於理解:
tz@Teaching Building NO.4 HZAU
2018/3/17