LeetCode75——Day24

文章目录

一、题目

2390. Removing Stars From a String

You are given a string s, which contains stars *.

In one operation, you can:

Choose a star in s.

Remove the closest non-star character to its left, as well as remove the star itself.

Return the string after all stars have been removed.

Note:

The input will be generated such that the operation is always possible.

It can be shown that the resulting string will always be unique.

Example 1:

Input: s = "leet**cod*e"

Output: "lecoe"

Explanation: Performing the removals from left to right:

  • The closest character to the 1st star is 't' in "leet**code". s becomes "leecod*e".
  • The closest character to the 2nd star is 'e' in "leecode". s becomes "lecod*e".
  • The closest character to the 3rd star is 'd' in "lecod*e". s becomes "lecoe".
    There are no more stars, so we return "lecoe".
    Example 2:

Input: s = "erase*****"

Output: ""

Explanation: The entire string is removed, so we return an empty string.

Constraints:

1 <= s.length <= 105

s consists of lowercase English letters and stars *.

The operation above can be performed on s.

二、题解

利用解决问题

cpp 复制代码
class Solution {
public:
    string removeStars(string s) {
        int n = s.length();
        stack<char> st;
        string res = "";
        for(int i = 0;i < n;i++){
            char c = s[i];
            if(c != '*') st.push(c);
            else if(c == '*' && !st.empty()) st.pop();
        }
        while(st.size()) res += st.top(),st.pop();
        reverse(res.begin(),res.end());
        return res;
    }
};
相关推荐
青山木2 分钟前
Hot 100 --- 最小栈
java·数据结构·算法·leetcode
疯狂打码的少年5 分钟前
【数据结构】栈的应用:表达式求值(后缀表达式)
java·数据结构·笔记·算法
HiDev_16 分钟前
【非标自动化】plc执行顺序问题、扫描周期问题
深度学习·算法·机器学习
高洁011 小时前
工信部教考中心证书-人工智能系列本系列
人工智能·python·深度学习·算法
10岁的博客1 小时前
【C++题解】最多共线点问题:小飞拿蛋糕游戏的最优策略
c++
陈王卜1 小时前
Reduce 算子优化笔记
算法
wabs6661 小时前
关于图论【最短路径之Bellman_ford 算法(判断负权回路)|卡码网95.城市间货物运输II的思考】
数据结构·算法·图论·bellman_ford算法·卡码网·判断负权回路
東隅已逝,桑榆非晚1 小时前
类和对象(中)
c++·笔记
YouonlyliveonceC1 小时前
《大话数据结构》第4章实战:中缀表达式转后缀 + 后缀表达式求值(完整可运行实现)
算法
phoenix@Capricornus2 小时前
从统计决策到贝叶斯估计
人工智能·算法·机器学习