给你一个包含若干星号 * 的字符串 s 。
在一步操作中,你可以:
选中 s 中的一个星号。
移除星号 左侧 最近的那个 非星号 字符,并移除该星号自身。
返回移除 所有 星号之后的字符串。
注意:
生成的输入保证总是可以执行题面中描述的操作。
可以证明结果字符串是唯一的。
地址:https://leetcode.cn/problems/removing-stars-from-a-string/description/?envType=study-plan-v2&envId=leetcode-75
实现思路: 栈
遍历字符串s,如果s[i]不为 ‘’ 则入栈,如果为 '’ 则统计 ‘*’ 的个数并出栈相应个数的字符串
func removeStars(s string) string {
stackStr := []uint8{} // 定义栈
length := len(s)
stars := 0 // 统计 * 的个数
change := false
for i := 0; i < length; i++ {
if s[i] != '*' {
// 入栈
stackStr = append(stackStr, s[i])
} else {
change = true
for i < length && s[i] == '*' {
stars++
i++
}
}
// 在入栈for遍历的最后一次会使i多加一次,这一次会使一个字符串没有入栈,所以i--
if change {
change = false
i--
}
// 出栈
stackStr = stackStr[:len(stackStr)-stars]
stars = 0
}
return string(stackStr)
}