Re: [闲聊] 每日LeetCode

楼主: pandix (面包屌)   2023-04-11 14:05:50
2390. Removing Stars From a String
给你一个包含 '*' 的字串,执行以下操作后回传结果
1.挑一个 '*',移除他和他左边第一个非 '*' 的字符
2.重复 1. 直到字串中没有 '*'
input string 会保证每个 '*' 都找的到消除对象
另外不管移除顺序为何结果都会一样
Example 1:
Input: s = "leet**cod*e"
Output: "lecoe"
Explanation: Performing the removals from left to right:
Example 2:
Input: s = "erase*****"
Output: ""
思路:
1.看到移除左边第一个应该很容易能想到用 stack
从左到右把字串放进 stack 里 遇到 '*' 就直接 pop 掉 stack 顶部就好
'*' 不会进 stack 所以不用额外判断
Python code:
class Solution:
def removeStars(self, s: str) -> str:
stk = []
for c in s:
if c == '*':
stk.pop()
else:
stk.append(c)
return ''.join(stk)
作者: h0103661 (路人喵)   2023-04-11 16:39:00
今天这题底下十几个人问为什么会TLE,好奇怪

Links booklink

Contact Us: admin [ a t ] ucptt.com