友情链接 Doge博客 gunpowder博客 东北小蟹蟹博客

C++左右括号匹配问题(并给出括号的位置 并且允许非括号字符插入)修改版

#include<iostream>
#include<algorithm>
#include<stack>
#include<map>
#include<string>
#include<malloc.h>
using namespace std;
struct _Token{
int begin;
int end;
}Token;
int main(){
	void match(string s,_Token *data);
	_Token *data=(_Token*)calloc(1024,sizeof(Token));
	string ss;
	cin>>ss;
	match(ss,data);
	for(int i=0;data[i].begin!=0&&data[i].end!=0;i++)
	printf("%d %d\n",data[i].begin,data[i].end);
	return 0;
}
void match(string s,_Token *data){
stack<char>st;
stack<int>num;
map<int ,int>m;
int flag=0;
	for(int i=0;s[i];i++){
	   if(st.empty()){
	   	  st.push(s[i]);
	   	  num.push(i+1);
			 i++;
	   }
		char temp=st.top();
		if(temp==')'){
			flag=1;break;
		}
	    else if(temp=='('&&s[i]==')'){
	    	int tnum=num.top();num.pop();
	    	m[tnum]=i+1;
	    	st.pop();
		}
		else if(/*temp!='('&&temp!=')'&&*/s[i]!='('&&s[i]!=')'){
         //"吃"掉既不属于'('也不属于')这种情况'
		}
		else {
			st.push(s[i]);
			num.push(i+1);
		}
	}
	int ab=0;
	if(flag==1||!st.empty())return;
	else{
		for(map<int,int>::iterator it=m.begin();it!=m.end();++it,ab++){
			//cout<<it->first<<" "<<it->second<<endl;
			data[ab].begin=it->first;
			data[ab].end=it->second;
		}
	}
}

}

添加非括号字符的支持
原始代码:

NULL

修改后代码最终效果:

NULL

GitHub托管的VS2017 dll工程:https://github.com/3XDot/GetToken
参考:https://blog.csdn.net/zxk_hi/article/details/79007663

posted @ 2021-04-05 08:43  Ruptpsych  阅读(150)  评论(0编辑  收藏  举报