Leetcode3174. 清除数字
Every day a Leetcode
题目来源:3174. 清除数字
解法1:栈
用栈模拟,遇到数字就弹出栈顶,遇到字母就插入栈。
最后留在栈里的就是答案。
代码:
/** @lc app=leetcode.cn id=3174 lang=cpp** [3174] 清除数字*/// @lc code=start
class Solution
{
public:string clearDigits(string s){stack<char> stk;for (char &c : s){if (isdigit(c))stk.pop();elsestk.push(c);}string ans;while (!stk.empty()){ans.insert(ans.begin(), stk.top());stk.pop();}return ans;}
};
// @lc code=end
结果:
复杂度分析:
时间复杂度:O(n),其中 n 是字符串 s 的长度。
空间复杂度:O(n),其中 n 是字符串 s 的长度。