61
61
62
62
** 方法一:栈模拟**
63
63
64
- 我们可以使用栈模拟操作过程。
65
-
66
- 遍历字符串 $s$,如果当前字符不是星号,则将其入栈;如果当前字符是星号,则将栈顶元素出栈。
64
+ 我们可以使用栈模拟操作过程。遍历字符串 $s$,如果当前字符不是星号,则将其入栈;如果当前字符是星号,则将栈顶元素出栈。
67
65
68
66
最后我们将栈中元素拼接成字符串返回即可。
69
67
78
76
``` python
79
77
class Solution :
80
78
def removeStars (self , s : str ) -> str :
81
- stk = []
79
+ ans = []
82
80
for c in s:
83
81
if c == ' *' :
84
- stk .pop()
82
+ ans .pop()
85
83
else :
86
- stk .append(c)
87
- return ' ' .join(stk )
84
+ ans .append(c)
85
+ return ' ' .join(ans )
88
86
```
89
87
90
88
### ** Java**
@@ -94,15 +92,15 @@ class Solution:
94
92
``` java
95
93
class Solution {
96
94
public String removeStars (String s ) {
97
- StringBuilder sb = new StringBuilder ();
98
- for (char c : s . toCharArray() ) {
99
- if (c == ' *' ) {
100
- sb . deleteCharAt(sb . length() - 1 );
95
+ StringBuilder ans = new StringBuilder ();
96
+ for (int i = 0 ; i < s . length(); ++ i ) {
97
+ if (s . charAt(i) == ' *' ) {
98
+ ans . deleteCharAt(ans . length() - 1 );
101
99
} else {
102
- sb . append(c );
100
+ ans . append(s . charAt(i) );
103
101
}
104
102
}
105
- return sb . toString();
103
+ return ans . toString();
106
104
}
107
105
}
108
106
```
@@ -115,8 +113,11 @@ public:
115
113
string removeStars(string s) {
116
114
string ans;
117
115
for (char c : s) {
118
- if (c == '* ') ans.pop_back();
119
- else ans.push_back(c);
116
+ if (c == '* ') {
117
+ ans.pop_back();
118
+ } else {
119
+ ans.push_back(c);
120
+ }
120
121
}
121
122
return ans;
122
123
}
@@ -143,15 +144,15 @@ func removeStars(s string) string {
143
144
144
145
``` ts
145
146
function removeStars(s : string ): string {
146
- const stack = [];
147
+ const ans : string [] = [];
147
148
for (const c of s ) {
148
149
if (c === ' *' ) {
149
- stack .pop ();
150
+ ans .pop ();
150
151
} else {
151
- stack .push (c );
152
+ ans .push (c );
152
153
}
153
154
}
154
- return stack .join (' ' );
155
+ return ans .join (' ' );
155
156
}
156
157
```
157
158
@@ -160,15 +161,15 @@ function removeStars(s: string): string {
160
161
``` rust
161
162
impl Solution {
162
163
pub fn remove_stars (s : String ) -> String {
163
- let mut res = String :: new ();
164
+ let mut ans = String :: new ();
164
165
for & c in s . as_bytes (). iter () {
165
166
if c == b '*' {
166
- res . pop ();
167
+ ans . pop ();
167
168
} else {
168
- res . push (char :: from (c ));
169
+ ans . push (char :: from (c ));
169
170
}
170
171
}
171
- res
172
+ ans
172
173
}
173
174
}
174
175
```
0 commit comments