Skip to content

Commit 306e04f

Browse files
Remove stars from string
1 parent 232efbd commit 306e04f

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Remove-Stars-From-String/solution.js

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
// 2390. Removing Stars From a String
2+
3+
// Problem statement
4+
5+
// You are given a string s, which contains stars *.
6+
// In one operation, you can:
7+
// Choose a star in s.
8+
// Remove the closest non-star character to its left, as well as remove the star itself.
9+
// Return the string after all stars have been removed.
10+
11+
// Note:
12+
// The input will be generated such that the operation is always possible.
13+
// It can be shown that the resulting string will always be unique.
14+
15+
// Understand the problem first...
16+
17+
// hme aik string `s` ke name se dia gia hy hum ne is string me se star ko remove krna hy aur str ke left pe jo letter hy us ko bi remove krna hy aur then string return kr dena hy agr koi bi nahi milta tu pir empty string return kr dena hy.
18+
19+
// Solution
20+
21+
// is problem ko hal krne ke liye hum log stack data structire ka use kre ge. sb se pehle hum aik stack initialize kre ge then us string per loop lga ke hr hr letter ko nikal le ge then hum ye dekhe ke agr ane wala character * se match krta hy tu us se left wale ko remove kr do warna append kr do. aik baat yaad rakhe ke hum comapre tb hi kr paye ge jb stack me kuch ho ga. Then is stack ko string me return kr de ge.
22+
23+
let removeStars = function (s) {
24+
let stack = [];
25+
for (let letter of s) {
26+
if (stack && letter === "*") {
27+
stack.pop(stack[stack.length - 1]);
28+
} else {
29+
stack.push(letter);
30+
}
31+
}
32+
return stack.join("");
33+
};
34+
35+
console.log(removeStars("leet**cod*e"));
36+
console.log(removeStars("erase*****"));
37+
38+
// e ===> 0 pop
39+
// r ===> 1 pop
40+
// a ===> 2 pop
41+
// s ===> 3 pop
42+
// e ===> 4 pop
43+
// * ===> 5 pop
44+
// * ===> 6 pop
45+
// * ===> 7 pop
46+
// * ===> 8 pop
47+
// * ===> 9 pop

0 commit comments

Comments
 (0)