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;
    }
};
相关推荐
侯小啾20 分钟前
【23】C语言 左移(<<) 与 右移(>>) 位运算符在处理像素中的应用
c语言·算法·位运算·右移·左移
搂鱼11451429 分钟前
(dp 优化)洛谷 P14460 寻雾启示 题解
算法·图论
阿林学习计算机37 分钟前
C++11特性
c++
_OP_CHEN41 分钟前
算法基础篇:(十一)贪心算法拓展之区间问题:从重叠到覆盖的最优解艺术
算法·贪心算法
Elias不吃糖1 小时前
NebulaChat:C++ 高并发聊天室服务端
开发语言·c++·redis·sql·项目文档
帅中的小灰灰1 小时前
C++编程策略设计模式
开发语言·c++·设计模式
钟智强1 小时前
线性映射(Linear Mapping)原理详解:机器学习中的数学基石
人工智能·算法·机器学习
是小胡嘛2 小时前
华为云CentOS系统中运行http服务器无响应
linux·服务器·c++·http·centos·华为云
Sylvia-girl2 小时前
数据结构之线性表中的顺序表(1)
数据结构
福尔摩斯张3 小时前
C语言核心:string函数族处理与递归实战
c语言·开发语言·数据结构·c++·算法·c#