算法(四)字符串转化为整数相加
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; } };
相关文章推荐
- 字符串转化为整数的算法改进及优化
- 字符串转化为整数的算法改进及优化
- 字符串转化为整数的算法改进及优化
- 【算法题】整数与字符串之间的相互转化
- 经典算法-字符串转化为整数
- 算法(二)字符串转化为整数
- 两个大整数相加算法
- JavaScript趣题:大整数字符串相加
- 编程实现字符串转化为整数的办法
- 程序员面试题精选100题(17)-把字符串转换成整数[算法]
- 将字符串转化为整数问题(C++)
- 将整形整数转化为数组的形式分别依次存到数组当中,然后倒叙输出、把原本字符串倒序输出。截取字符串等等
- 给定一个整数,把整数中包含的每一个数字放到一个数组中(不要把数字转化为字符串处理)
- 整数转化为任意n进制的字符串
- 算法---大整数相加
- 剑指offer43--字符串转化成整数
- 把字符串转化为整数
- 面试算法(四十九)把字符串转换为整数
- Python:利用内建函数将字符串转化为整数
- PHP中将字符串转化为整数(int) intval() printf() 性能测试