C++之({[这三种符号匹配

SymbolMatchingalgorithm.h头文件

 

#pragma once
#include <string>
#include <map>

class CSymbolMatchingalgorithm
{
public:
CSymbolMatchingalgorithm();
~CSymbolMatchingalgorithm();

public:
//完全匹配
bool matchAlgorithm(std::string& s, std::map<int, int>& searchMap);
bool matchAlgorithm(std::string& s);
//查找匹配所对应的位置,从0计数
bool searchPos(std::string& str, int pos, int& outPos);


};

 SymbolMatchingalgorithm.cpp文件

#include "stdafx.h"
#include "SymbolMatchingalgorithm.h"
#include<iOStream>
#include<stack>
#include<cstdlib>
#include<cstring>
#include <vector>

using namespace std;

CSymbolMatchingalgorithm::CSymbolMatchingalgorithm()
{
}


CSymbolMatchingalgorithm::~CSymbolMatchingalgorithm()
{
}


bool left(char s)
{
return s == '(' || s == '{' || s == '[';
}
bool right(char s)
{
return s == ')' || s == '}' || s == ']';
}
bool check(char a, char b)
{
return (a == '('&&b == ')') || (a == '{'&&b == '}') || (a == '['&&b == ']');
}

bool CSymbolMatchingalgorithm::matchAlgorithm(std::string& s, std::map<int, int>& searchMap)
{
stack<char> p;
bool flag = true;

int a = 0;
std::vector<int> pushvec;
for (int i = 0; i < s.length(); i++)
{
if (left(s[i]))
{
p.push(s[i]);
pushvec.push_back(a);
}
if (right(s[i]))
{
if (!p.empty() && check(p.top(), s[i]))
{
p.pop();
int b = pushvec[pushvec.size() - 1];
pushvec.erase(pushvec.begin() + pushvec.size() - 1);
searchMap[b] = a;
searchMap[a] = b;
}
else flag = false;
}
a++;
}
if (!p.empty())flag = false;
return flag;
}

bool CSymbolMatchingalgorithm::matchAlgorithm(std::string& s)
{
stack<char> p;
bool flag = true;
for (int i = 0; i < s.length(); i++)
{
if (left(s[i]))
{
p.push(s[i]);

}
if (right(s[i]))
{
if (!p.empty() && check(p.top(), s[i]))
{
p.pop();
}
else flag = false;
}
}
if (!p.empty())flag = false;
return flag;
}


bool CSymbolMatchingalgorithm::searchPos(std::string& str, int pos, int& outPos)
{
std::map<int, int> searchMap;
if (!matchAlgorithm(str, searchMap))
return false;

if (searchMap.count(pos) > 0)
{
outPos = searchMap[pos];
return true;
}
return false;
}

 

main函数:

string str = "1000-(sum()*2)";
CSymbolMatchingalgorithm matchOpera;
if (matchOpera.matchAlgorithm(str))
{
cout << "Yes" << endl;
}
else cout << "No" << endl;

int pos = 5;
int outpos;
if (matchOpera.searchPos(str, pos, outpos))
{
cout << "Yes" << outpos<<endl;
}

posted @ 2020-07-28 10:38  久龄  阅读(16)  评论(0编辑  收藏  举报