LeetCode 1598. 文件夹 *** 作日志搜集器

LeetCode 1598. 文件夹 *** 作日志搜集器,第1张

本来老老实实用的stack做的,但是后来发现可以直接使用int类型的ans记录层数,无需返回栈中的值。
本题复习了一下stack的创建,以及stack的判空/push/pop/求大小 *** 作;以及发现C++ 11 新特性中的增强型for循环中还能用string,其余都是简单 *** 作

原代码
class Solution {
public:
    int minOperations(vector<string>& logs) 
    {
        stack<string>stk;
        for(string str:logs)
        {
            if(str == "../")
            {
                if(!stk.empty())
                    stk.pop();
            }
            else if (str !="./")
                stk.push(str);
        }
        return stk.size();
    }
};
优化
class Solution {
public:
    int minOperations(vector<string>& logs) 
    {
        int ans = 0;
        for(string str:logs)        
        {
            if(str == "../")
            {
                if(ans != 0)
                    --ans;
            }
            else if (str !="./")
                ++ans;
        }
        return ans;
    }
};

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/2889644.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-09-14
下一篇2022-09-14

发表评论

登录后才能评论

评论列表(0条)

    保存