您的位置:首页 > 其它

算法(四)字符串转化为整数相加

2017-09-19 12:51 253 查看

题目描述:

Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, - and *.

题目解析:

采用分治的办法,遍历字符串,根据操作符将等式分为左右两部分,各自求值再进行相应的操作(+,-,*),每遍历到一个操作符就进行一次分裂操作,将运行后的结果放入一个vector容器中作为返回值。

代码如下:

class Solution {
public:
vector<int> diffWaysToCompute(string input) {
vector<int> temp = subResult(input);
return temp;
}
vector<int> subResult(string input) {
vector<int> result, temp1, temp2;
int i = 0, flag = 0;
for (; i < input.size(); ++i) {
if (input[i] == '+' || input[i] == '-' || input[i] == '*') {
flag = 1;
temp1 = subResult(input.substr(0, i));
temp2 = subResult(input.substr(i + 1, input.size() - i - 1));
for (vector<int>::iterator j = temp1.begin(); j != temp1.end(); ++j) {
for (vector<int>::iterator k = temp2.begin(); k != temp2.end(); ++k) {
if (input[i] == '+') result.push_back(*j + *k);
if (input[i] == '-') result.push_back(*j - *k);
if (input[i] == '*') result.push_back((*j) * (*k));
}
}
}
}
//如果字符串内已经没有操作符,则直接返回操作数。
if (flag == 0) {
int temp = 0;
for (int i = input.size() - 1; i >= 0; --i) {
temp += (input[i] - '0') *pow(10, (input.size() - i -1));
}
result.push_back(temp);
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: