给你一个包含若干星号 *
的字符串 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) 个元素。