括号配对问题——请选择合适的数据结构
2013-09-13 22:21:26
转自:http://blog.chinaunix.net/uid-24118190-id-3896712.html
C++的STL提供了一些封闭好的数据结构和算法,方便日常编程。
所谓 “工欲善其事,必先利其器。”请在学习了STL后,选择一种合适的工具来解决括号配对问题。
Containers library - cppreference.com
http://en.cppreference.com/w/cpp/container
这里使用stack解答了一个括号配对问题,但这个代码没有使用“最合适”的工具。
请选择一种合适的数据结构实现本题“扩展”要求:
点击(此处)折叠或打开
- /*
- 括号配对
- 配对原则: 3种括号()[]{}它们可以彼此包含,但不能交叉。
- 请实现 isValidSeq,测试给定字符串中括号是否正确配对。若括号匹配返回 true(1)。
- ref: http://blog.csdn.net/bxyill/article/details/8040983
- pz
- 2013-9-11
- 扩展(作业):
- {} 只允许被 {} 包含。
- 如:
- {([])} OK
- {{}[]} OK
- ({}) NG
- tip:
- 实现基本要求使用stack即可。
- 实现扩展要求需要一种能够遍历的stack,若当前字符是{则遍历栈中是否有其它括号。
- 即使用数组实现stack能够满足要求。
- */
- #include <iostream>
- #include <stack>
- #include <assert.h>
- using namespace std;
- bool isValidSeq(char *s);
- int main()
- {
- char *testdata[] = {// base,extend
- "()[]{}", // OK,OK
- "(([])){}", // OK,OK 多重括号
- "{(){}[]}", // OK,NG 嵌套:{}包含其它
- "(){{}[}]", // OK,NG 交叉:[}
- "(+){{*}[ ]} " // NG 夹杂非括号
- };
- for(int i=0; i<sizeof(testdata)/sizeof(testdata[0]); i++)
- {
- cout << i << " TEST: " << testdata[i] << endl;
- bool res = isValidSeq(testdata[i]);
- cout <<"Test result: "<< (char*)(res?"OK":"NG") << endl<< endl;
- }
- return 0;
- }
- // return:
- // {[{ -1-2-3
- // )]} +1+2+3
- // else 0
- int BracketType(char c)
- {
- int res = 0;
- if(c == '(')
- res = -1;
- else if(c == ')')
- res = 1;
- else if(c == '[')
- res = -2;
- else if(c == ']')
- res = 2;
- else if(c == '{')
- res = -3;
- else if(c == '}')
- res = 3;
- else
- res = 0;
- return res;
- }
- // 简单匹配
- bool isValidSeq(char *s)
- {
- assert(s != NULL);
- stack<int> st;
- int match = 0; // -1 err; 0 ign; 1 match
- for(char *p = s; *p != '\0'; p++)
- {
- int bt = BracketType(*p);
- if(bt == 0)
- match = 0;
- else if(bt < 0)
- {
- match = 0;
- st.push(bt);
- }
- else
- {
- if(st.empty())
- match = -1;
- if(st.top() == -bt)
- {
- match = 1;
- st.pop();
- }
- else
- match = -1;
- }
- cout<< *p ;
- if(match == -1)
- {
- cout<<" mismatch" <<endl;
- return 0;
- }
- else if(match == 1)
- cout<<" match" <<endl;
- }
- //cout<<endl;
- return st.empty();
- }

浙公网安备 33010602011771号