LeetCode 2390. 从字符串中移除星号

2390. 从字符串中移除星号

给你一个包含若干星号 * 的字符串 s 。

在一步操作中,你可以:

  • 选中 s 中的一个星号。
  • 移除星号 左侧 最近的那个 非星号 字符,并移除该星号自身。

返回移除 所有 星号之后的字符串

注意:

  • 生成的输入保证总是可以执行题面中描述的操作。
  • 可以证明结果字符串是唯一的。

示例 1:

输入:s = "leet**cod*e"
输出:"lecoe"
解释:从左到右执行移除操作:
- 距离第 1 个星号最近的字符是 "leet**cod*e" 中的 't' ,s 变为 "lee*cod*e" 。
- 距离第 2 个星号最近的字符是 "lee*cod*e" 中的 'e' ,s 变为 "lecod*e" 。
- 距离第 3 个星号最近的字符是 "lecod*e" 中的 'd' ,s 变为 "lecoe" 。
不存在其他星号,返回 "lecoe" 。

示例 2:

输入:s = "erase*****"
输出:""
解释:整个字符串都会被移除,所以返回空字符串。

提示:

  • 1 <= s.length <= 10^5
  • s 由小写英文字母和星号 * 组成
  • s 可以执行上述操作

提示 1

What data structure could we use to efficiently perform these removals?


提示 2

Use a stack to store the characters. Pop one character off the stack at each star. Otherwise, we push the character onto the stack.

解法1:模拟

使用变长数组对栈进行模拟。

Java版:

class Solution {
    public String removeStars(String s) {
        StringBuffer str = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '*') {
                if (str.length() > 0) {
                    str.delete(str.length() - 1, str.length());
                }
            } else {
                str.append(s.charAt(i));
            }
        }
        return str.toString();
    }
}

Python3版

class Solution:
    def removeStars(self, s: str) -> str:
        ans = []
        for ch in s:
            if ch == '*':
                if len(ans) > 0:
                    ans.pop() 
            else:
                ans.append(ch)
        return "".join(ans)

复杂度分析

  • 时间复杂度:O(n),其中 n 为字符串 s 的大小。遍历整个 s 需要 O(n)。
  • 空间复杂度:O(n)。变长数组最多保存 O(n) 个元素。
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值