您的位置:首页 > 编程语言 > C语言/C++

用C++ 语言如何实现表达式拆分“1*2*3*(4+(5+6)*(7+8))+9”

2016-01-22 12:47 357 查看
问题:用C++ 语言如何实现表达式拆分

把一个字符串形式的数学表达式以拆加号为原则,一级一级拆分,最终汇总为一个字符串数组。数学表达式是由”+”、”(“、”)”和数字组成。

示例如下:

1、字符串表达式为:1*2*3*(4+(5+6)*(7+8))+9

拆分最终的字符串数组结果为(数组元素排序没有要求):

1*2*3*4

1*2*3*5*7

1*2*3*5*8

1*2*3*6*7

1*2*3*6*8

9

// C++11


代码如下:

#include <iostream>
#include <string>
#include <vector>

std::vector<std::string> processexp(const std::string &sexp);

int main()
{

std::string sexp;

std::getline(std::cin, sexp);
std::cout << sexp << std::endl;

std::vector<std::string> svret = processexp(sexp);

for (const auto &i : svret) {
std:: cout << i << std::endl;
}
return 0;
}

std::vector<std::string> processexp(const std::string &sexp)
{
std::vector<std::string> svec;
std::vector<std::string> destsvec;
std::vector<std::string> midsvec;

std::string read;
char c;

for (std::string::size_type i = 0; i < sexp.size(); i++) {
c = sexp[i];
switch (c) {
case '*':
{
if (!read.empty()) {
svec.push_back(read);
read.clear();
}
svec.emplace_back(1, c);
}
break;
case '(':
{
std::string::size_type m, n, p1, p2;
m = i;
while (true) {
m += 1;
p1 = sexp.find_first_of('(', m);
p2 = sexp.find_first_of(')', m);
if (p1 != std::string::npos && p1 < p2) {
m = p2;
continue;
}
n = p2;
break;
}
std::string subexp = sexp.substr(i+1, n - i - 1);
std::vector<std::string> sv = processexp(subexp);
if (i > 1 && sexp[i-1] != '*'
&& n + 1 < sexp.size() && sexp[n+1] == '*') {
midsvec = sv;
i = n;
break;
}

std::string bfexp;
for (const auto &e : svec) {
bfexp += e;
}
svec.clear();
std::vector<std::string> desttemp{midsvec};
midsvec.clear();
for (const auto &e : sv) {
if (!desttemp.empty()) {
for (const auto &e2 : desttemp) {
auto e3 = e2 + bfexp + e;
midsvec.push_back(e3);
}
} else {
midsvec.push_back(bfexp+e);
}
}
if (n + 1 < sexp.size() && sexp[n+1] == '*') {
#if 0
for (const auto &e : destsvec) {
std::cout << "|<<<" << e << "|";
}
std::cout << std::endl;
#endif
} else {
destsvec.insert(destsvec.end(), midsvec.begin(), midsvec.end());
midsvec.clear();
}
i = n;
}
break;
case '+':
{
if (!read.empty()) {
svec.push_back(read);
}
std::string all;
for (const auto &e : svec) {
all += e;
}

if (!all.empty()) {
std::vector<std::string> desttemp{midsvec};
midsvec.clear();
if (!desttemp.empty()) {
for (const auto &e2 : desttemp) {
auto e3 = e2 + all;
destsvec.push_back(e3);
}
} else {
destsvec.push_back(all);
}
}
svec.clear();
read.clear();
}
break;
default:
read += c;
break;
}
}
if (!read.empty()) {
svec.push_back(read);
}
std::string all;
for (const auto &e : svec) {
all += e;
}
if (!all.empty()) {
std::vector<std::string> desttemp{midsvec};
midsvec.clear();
if (!desttemp.empty()) {
for (const auto &e2 : desttemp) {
auto e3 = e2 + all;
destsvec.push_back(e3);
}
} else {
destsvec.push_back(all);
}
}

return destsvec;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: