#include <iostream>
#include <stack>
#include <string>
#include <regex>
using namespace std;
bool priority(char top, char b){
if(top == '('){//为左括号
return false;
}
if(top == '-' || top == '+' && b == '*'){
return false;//高则压栈
}
if((top == '+' || top == '-') && (b == '+' || b == '-')){
return false;
}
else{
return true;//计算
}
}
void compute(stack<int>& s1, stack<char>& s2){
int b = s1.top();
s1.pop();
int a = s1.top();
s1.pop();
char ch = s2.top();
s2.pop();
int sum = 0;
if(ch == '+'){
sum = a + b;
}
else if(ch == '-'){
sum = a - b;
}
else{
sum = a*b;
}
s1.push(sum);
}
int main() {
//先找到最长的数学表达式子
string s;
getline(cin, s);
//查找最长合法数学表达式
regex math("(-?\\d+)([\\*+-]\\d+)*"); // 定义正则表达式,匹配数字和操作符序列
sregex_iterator it(s.begin(), s.end(), math);//允许遍历一个字符串中所有符合正则表达式的子串
sregex_iterator end;
string longstr = "";
while(it != end){
if(it->str().size() > longstr.size()){
longstr = it->str();
}
it++;
}
longstr = longstr + ')';//加上右括号
stack<int> arr;
stack<char> symbol;
string temp = "";
symbol.push('(');//先压入左括号
bool flag = false;//标记是负号还是减号
for(int i = 0; i < longstr.size(); i++){
if(longstr[i] >= '0' && longstr[i <='9']){
temp += longstr[i];
}
else if(longstr[i] == ')'){//如果是右括号
flag = false;//后续的第一个-为负号
arr.push(stoi(temp));
temp = "";
while(symbol.top()!='('){
compute(arr, symbol);
}
symbol.pop();
}
else if(longstr[i] == '-'){
if(!flag){//第一次出现-
temp += '-';
flag = true;
}
else{//是符号
arr.push(stoi(temp));
temp = "";
while(priority(symbol.top(), longstr[i])){
compute(arr, symbol);
}
symbol.push(longstr[i]);//不计算,压栈
}
}
else{//是其他符号
flag = true;//下次遇到的-为符号
arr.push(stoi(temp));
temp = "";
while(priority(symbol.top(), longstr[i])){
compute(arr, symbol);
}
symbol.push(longstr[i]);
}
}
cout << arr.top() << endl;
}
提取字符串中最长的数学表达式并计算(C++)
最新推荐文章于 2024-07-10 08:50:24 发布