概述
匹配(),{},[],如果遇到/*,要跳过/*....*/之间的所有字符,如果没有*/,不匹配。
#include <iostream>
#include <string>
using namespace std;
template <class T>
class Stack{
private:
int maxSize;
int top;
T * st;
public:
Stack(int size){
maxSize = size;
top = -1;
st = new T[maxSize];
}
bool isEmpty()const;
bool isFull()const;
void push(const T & t);
void pop();
T & Top();
int Size()const;
~Stack(){}
};
template<class T>
bool Stack<T>::isEmpty()const{
return top==-1;
}
template<class T>
bool Stack<T>::isFull() const{
return top == maxSize-1;
}
template<class T>
void Stack<T>::push(const T&t){
if(!isFull()){
st[++top] = t;
}
else
cout<<"The stack is fulln";
}
template<class T>
void Stack<T>::pop(){
if(!isEmpty()){
top--;
}
else cout<<"Stack is emptyn";
}
template<class T>
T& Stack<T>::Top(){
if(!isEmpty()){
T el = st[top];
return el;
}
else{
char a;
a = 'm';
return a;
}
}
template<class T>
int Stack<T>::Size()const{
return top+1;
}
bool delimiterMatching(string str){
int len = str.length();
Stack<char> s(len);
char ch;
int i =0;
while(i<len){
ch = str[i];
if(ch == '('||ch=='['||ch=='{'){
s.push(ch);
i++;
}
else if(ch ==')'){
if(s.Top()=='('){
s.pop();
}
else{
cout<<"missing (,not matchn";
return 0;
}
i++;
}
else if(ch==']'){
if(s.Top()=='['){
s.pop();
}
else{
cout<<"missing [,not matchn";
return 0;
}
i++;
}
else if(ch=='}'){
if(s.Top()=='{'){
s.pop();
}
else{
cout<<"missing {,not matchn";
return 0;
}
i++;
}
else if(ch=='/'){
if(str[i+1] == '*'){
i++;
i++;
s.push('/');
s.push('*');
while(i<len-2){
if(str[i]=='*'&&str[i+1]=='/'){
s.pop();
s.pop();
i++;
i++;
break;
}
else{
i++;
}
}
}
else{
i++;
}
}
else{
i++;
}
}
if(s.isEmpty()){
return 1;
}
else{
if(s.Top() == '(')
{
cout <<"missing ')'"<<endl;
s.pop();
}
else if(s.Top() == '{')
{
cout <<"missing '}'"<<endl;
s.pop();
}
else if(s.Top() == '[')
{
cout <<"missing ']'"<<endl;
s.pop();
}
else if(s.Top() == '*')
{
cout <<"missing '*/'"<<endl;
s.pop();
}
return 0;
}
}
int main()
{
string str1 = "[s{=/*33212*/2}3]";
if(delimiterMatching(str1))
cout <<str1<<" is matching!n";
else
cout<<str1 <<" is not matchingn";
string str2 = "[s{=/*332122}3]";
if(delimiterMatching(str2))
cout <<str2<<" is matching!n";
else
cout<<str2<<" is not matchingn";
return 0;
}
最后
以上就是着急玫瑰为你收集整理的(C++) 分隔符匹配的全部内容,希望文章能够帮你解决(C++) 分隔符匹配所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复