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;
    }
};
相关推荐
启观川10 小时前
数据结构与算法 -第 3 章 常用算法-动态规划
数据结构·笔记·python·算法
码爸10 小时前
排序算法介绍
python·算法·排序算法
sm_9267870510 小时前
RFID 标签打印的技术实现要点与二次开发实践
java·大数据·前端·c++·编辑器
by2099910 小时前
C++ 多态:同一个基类接口,调用不同的函数
开发语言·c++·经验分享·多态
colinu10 小时前
C++ 异步任务与线程生命周期:`std::async`、`future`、`thread`、`jthread` 与协作式退出
java·jvm·c++
动词ing11 小时前
【题目练习】算法 组合总和||
算法
wuminyu11 小时前
ForkJoinPool窃取线程在扫描其他WorkQueue时的随机采样算法与Phase线程挂起唤醒机制解析
java·linux·c语言·jvm·c++
longlongzihan11 小时前
链表找环:Floyd 判圈算法(LeetCode 141 & 142 )
c++·算法·leetcode·链表
专业程序开发源11 小时前
flask家电故障预测系统92491-计算机课程设计/毕业设计
vscode·python·sql·算法·flask·课程设计
liulilittle11 小时前
Linux 下 select 测试函数
linux·服务器·网络·数据库·c++·select·c