2390. 从字符串中移除星号
2024-09-14 11:32:35

Problem: 2390. 从字符串中移除星号

思路

想到用栈维护,思路就很清晰了。

要想到使用栈,重点是注意到每次都是对最后一个元素进行操作的,正好符合栈的性质。

这题我错误地想使用双指针的做法来做,结果写法挺复杂不说,还TLE了。。。这就是没有抓住关键性质的后果。

复杂度

  • 时间复杂度: $O(n)$
  • 空间复杂度: $O(n)$

Code

[]
1
2
3
4
5
6
7
8
9
10
11
12
13
14

class Solution {
    public String removeStars(String s) {
        StringBuilder st = new StringBuilder();
        for (char c : s.toCharArray()) {
            if (c == '*') {
                st.deleteCharAt(st.length() - 1);
            } else {
                st.append(c);
            }
        }
        return st.toString();
    }
}