Skip to content

Latest commit

 

History

History
115 lines (96 loc) · 4.56 KB

0592._Fraction_Addition_and_Subtraction.md

File metadata and controls

115 lines (96 loc) · 4.56 KB

592. Fraction Addition and Subtraction

难度: Medium

刷题内容

原题连接

内容描述

Given a string representing an expression of fraction addition and subtraction, you need to return the calculation result in string format. The final result should be irreducible fraction. If your final result is an integer, say 2, you need to change it to the format of fraction that has denominator 1. So in this case, 2 should be converted to 2/1.

Example 1:
Input:"-1/2+1/2"
Output: "0/1"
Example 2:
Input:"-1/2+1/2+1/3"
Output: "1/3"
Example 3:
Input:"1/3-1/2"
Output: "-1/6"
Example 4:
Input:"5/3+1/3"
Output: "2/1"
Note:
The input string only contains '0' to '9', '/', '+' and '-'. So does the output.
Each fraction (input and output) has format ±numerator/denominator. If the first input fraction or the output is positive, then '+' will be omitted.
The input only contains valid irreducible fractions, where the numerator and denominator of each fraction will always be in the range [1,10]. If the denominator is 1, it means this fraction is actually an integer in a fraction format defined above.
The number of given fractions will be in the range [1,10].
The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int.

解题方案

思路 1 - 时间复杂度: O(N)- 空间复杂度: O(N)******

这个思路真的没啥好说的,就是最小公倍数和最大公约数稍微注意下怎么写就行,然后剩下的就是搬砖活了, 20分钟 bug free,一遍AC,莫名小自豪。。。。

class Solution(object):
    def fractionAddition(self, expression):
        """
        :type expression: str
        :rtype: str
        """
        def gcd(a, b):
            if a == 0:
                return b
            return gcd(b % a, a)
                
        def gcm(num1, num2):
            return num1 * num2 // gcd(num1, num2)

        def is_sign(expression, index): # 判断符号'-'是否是描述负数的符号
            if expression[i] == '-': 
                if i - 1 < 0 or expression[i - 1] in oprs:
                    return True
            return False

        oprs = '+-'
        units = []  # 保存包含操作符和操作数的列表
        start = 0  # 标记数字起点
        for i in range(len(expression)):
            if expression[i] in oprs:
                if not is_sign(expression, i):
                    units.append(expression[start:i])
                    units.append(expression[i])
                    start = i + 1
        units.append(expression[start:])
        while len(units) > 1:
            left, right = 0, 0
            gcmm = gcm(int(units[0].split('/')[1]), int(units[2].split('/')[1]))
            if units[0].split('/')[0][0] == '-':
                left = int(units[0].split('/')[0].lstrip('-')) * gcmm // int(units[0].split('/')[1]) * (-1)
            else:
                left = int(units[0].split('/')[0].lstrip('-')) * gcmm // int(units[0].split('/')[1])
            right = int(units[2].split('/')[0]) * gcmm // int(units[2].split('/')[1])
            if units[1] == '+':
                units = [str(left + right) + '/' + str(gcmm)] + units[3:]
            else:
                units = [str(left - right) + '/' + str(gcmm)] + units[3:]
        if units[0].split('/')[0].lstrip('-') == '0':
            res = units[0].split('/')[0] + '/1'
        else:
            gcdd = gcd(int(units[0].split('/')[0].lstrip('-')), int(units[0].split('/')[1]))
            # print('gcdd',gcdd)
            if units[0].split('/')[0][0] == '-':
                res = '-' + str(int(units[0].split('/')[0].lstrip('-'))//gcdd) + '/' + str(int(units[0].split('/')[1])//gcdd)
            else:
                res = str(int(units[0].split('/')[0].lstrip('-'))//gcdd) + '/' + str(int(units[0].split('/')[1])//gcdd)

        return res

思路 2 - 时间复杂度: O(N)- 空间复杂度: O(N)******

我怕不是个智障吧,还小自豪,。。。。看了discuss里面lee215大神的答案,我tm。。。。

class Solution(object):
    def fractionAddition(self, expression):
        """
        :type expression: str
        :rtype: str
        """
        from fractions import Fraction
        res = sum(map(Fraction, expression.replace('+', ' +').replace('-', ' -').split()))
        return str(res.numerator) + '/' + str(res.denominator)