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;
    }
};
相关推荐
Navigator_Z8 小时前
LeetCode //C - 1323. Maximum 69 Number
c语言·算法·leetcode
geovindu9 小时前
python:Lasso
开发语言·后端·python·算法
AAA修煤气灶刘哥10 小时前
同一个模型,为什么还要专门练一遍怎么用工具?
人工智能·后端·算法
csdn_aspnet10 小时前
C++ 求给定点集的简单闭合路径(Find Simple Closed Path for a given set of points)
c++
艾莉丝努力练剑10 小时前
【AI接入大模型SDK】解决接口连接异常问题
前端·c++·人工智能·学习·ai·架构
Severus_black10 小时前
【C++初阶】模板进阶
c语言·c++·学习
AAA修煤气灶刘哥11 小时前
两个 Agent 各自改得都对,合在一起为什么出错?
人工智能·后端·算法
电科_银尘11 小时前
【大模型算法与工程 34】QLoRA:量化底座上的低秩训练
人工智能·算法·机器学习
专注仿真11 小时前
智能体训练:模仿学习与 MCTS 算法详解与实战
算法·强化学习·仿真·afsim智能体·仿真训练
艾莉丝努力练剑12 小时前
【AI接入大模型SDK】Markdown格式解析
前端·c++·人工智能·学习·ai·架构