力扣题:数字与字符串间转换-12.15

力扣题-12.15

[力扣刷题攻略] Re:从零开始的力扣刷题生活

力扣题1:592. 分数加减运算

解题思想:首先通过+对表达式进行分离,然后利用分数的加法原则进行计算,最后除以最大公因数即可

力扣题:数字与字符串间转换-12.15_第1张图片

class Solution(object):
    def fractionAddition(self, expression):
        """
        :type expression: str
        :rtype: str
        """
        modified_expression = expression.replace('-', '+-')
        temp = modified_expression.split("+")
        up = 0
        down = 1

        for i in range(len(temp)):
            if temp[i] != '':
                temp_up = int(temp[i].split('/')[0])
                temp_down = int(temp[i].split('/')[1])
                up = up * temp_down + down * temp_up
                down = down * temp_down
        for j in range(min(abs(up),abs(down)),1,-1):
            if down%j == 0 and up%j ==0:
                down = down/j
                up = up/j
                break
        if up == 0:
            return "0/1"
        else:
            return str(int(up)) + "/" + str(int(down))
class Solution {
public:
    string fractionAddition(string expression) {
        std::string modified_expression = replace_minus_with_plus_dash(expression);
        
        std::vector<std::string> temp = split_expression(modified_expression, '+');
        
        int up = 0;
        int down = 1;

        for (size_t i = 0; i < temp.size(); ++i) {
            if (!temp[i].empty()) {
                int temp_up = std::stoi(split_fraction(temp[i], '/')[0]);
                int temp_down = std::stoi(split_fraction(temp[i], '/')[1]);
                up = up * temp_down + down * temp_up;
                down = down * temp_down;
            }
        }

        for (int j = std::min(std::abs(up), std::abs(down)); j > 1; --j) {
            if (down % j == 0 && up % j == 0) {
                down = down / j;
                up = up / j;
                break;
            }
        }

        if (up == 0) {
            return "0/1";
        } else {
            return std::to_string(up) + "/" + std::to_string(down);
        }
    }

private:
    std::string replace_minus_with_plus_dash(std::string str) {
        size_t found = str.find("-");
        while (found != std::string::npos) {
            str.replace(found, 1, "+-");
            found = str.find("-", found + 2);
        }
        return str;
    }

    std::vector<std::string> split_expression(std::string str, char delimiter) {
        std::vector<std::string> result;
        size_t pos = 0;
        while ((pos = str.find(delimiter)) != std::string::npos) {
            result.push_back(str.substr(0, pos));
            str.erase(0, pos + 1);
        }
        result.push_back(str);
        return result;
    }

    std::vector<std::string> split_fraction(std::string str, char delimiter) {
        std::vector<std::string> result;
        size_t pos = str.find(delimiter);
        result.push_back(str.substr(0, pos));
        result.push_back(str.substr(pos + 1));
        return result;
    }
};

你可能感兴趣的:(leetcode,算法,职场和发展)