
本来老老实实用的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;
}
};
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)