字符串中圆括号的平衡和匹配检测

来源:互联网 发布:网络诈骗电话多少 编辑:程序博客网 时间:2024/05/18 00:04

匹配和平衡:例如 ((()()));

不平衡:)();

不匹配:());

检测算法提示:从左到右扫描一个合法的字符串,保证任何时候所遇到的右圆括号不会比左圆括号多。

 

 代码示例:

bool isBalanceOrMatch(char* arr, int n){int leftC = 0;int rightC = 0;for (int i=0; i<n; i++){char c = arr[i];switch(c){case '(':leftC++;break;case ')':rightC++;    break;default:    break;}if (rightC > leftC){return false;}}return true;}


 

原创粉丝点击