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

题目描述:

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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值