Fraction Addition and Subtraction (Leetcode 592)

给出一个直观的解法,将每个数写成 "+(nom)/(denom)" 的string形式放到deque里,然后再把deque两两计算合并。计算时,要用到gcd来消公约数。写的比较长。

class Solution {
public:
    
    int gcd(int a, int b){
        return b == 0 ? a : gcd(b, a % b);
    }
    
    string calculate(string s1, string s2){

        int idx1 = s1.find_first_of('/'), idx2 = s2.find_first_of('/');
        int nom_1 = stoi(s1.substr(0, idx1)), nom_2 = stoi(s2.substr(0, idx2));
        int denom_1 = stoi(s1.substr(idx1+1)), denom_2 = stoi(s2.substr(idx2+1));
        int res_denom = denom_1 * denom_2; 
        int res_nom = nom_1 * denom_2 + nom_2 * denom_1;
        if(res_nom == 0) return"+0/1";
        
        int common = gcd(abs(res_nom), abs(res_denom));
        res_nom /= common; res_denom /= common;
        
        int sign = (res_nom * res_denom < 0) ? -1 : 1;
        return (sign == 1 ? '+' : '-') + to_string(abs(res_nom)) + '/' + to_string(abs(res_denom));
        
    }

    string fractionAddition(string expression) {
        if(expression.empty()) return "";
        if(isdigit(expression[0])) expression.insert(expression.begin(), '+');
        
        deque<string> dq;
        int start = 0;
        for(int i=1; i<=expression.length(); i++){
            if( i == expression.length() || expression[i] == '+' || expression[i] == '-'){
                string temp = expression.substr(start, i-start);
                dq.push_back(temp);
                start = i;
            }
        }
        while(dq.size() >= 2){
            string s1 = dq.front(); dq.pop_front();
            string s2 = dq.front(); dq.pop_front();
            string res = calculate(s1, s2);
            //cout << s1 << " " << s2 << " " << res << endl;
            dq.push_front(res);
        }
        string res = dq.front();
        return res[0] == '-' ? res : res.substr(1);
    }
};

更简洁的solution参见如下,用regular expression split,再loop数组相加.

https://discuss.leetcode.com/topic/89991/concise-java-solution

其中,String[] fracs = expression.split("(?=[-+])"); 运用了zero-positive look ahead, 表明在+或-的前面split.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,774评论 0 33
  • LeetCode 刷题随手记 - 第一部分 前 256 题(非会员),仅算法题,的吐槽 https://leetc...
    蕾娜漢默阅读 17,933评论 2 36
  • 本来想说说,读心经的缘起,突然想起上次有几篇文章被锁定的事,再一搜索,宗教也在范围之内,那么少谈为妙。 之所以今天...
    墨语花开时阅读 349评论 4 3
  • 在那么一些无法入睡的夜晚,很多画面,会在一个莫名的夜晚集中出现,不知道为什么,大概很多事并真的没有过去,一...
    Lermon阅读 301评论 0 0
  • 生命里无疑还有许多夏天,但肯定没有一个夏天,会如今夏。 《忽而今夏》
    桐生千夏阅读 162评论 0 0