-
Notifications
You must be signed in to change notification settings - Fork 11
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
36112d5
commit 8998c83
Showing
1 changed file
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
/** | ||
2390. Removing Stars From a String | ||
Solved | ||
Medium | ||
Topics | ||
Companies | ||
Hint | ||
You are given a string s, which contains stars *. | ||
In one operation, you can: | ||
Choose a star in s. | ||
Remove the closest non-star character to its left, as well as remove the star itself. | ||
Return the string after all stars have been removed. | ||
Note: | ||
The input will be generated such that the operation is always possible. | ||
It can be shown that the resulting string will always be unique. | ||
**/ | ||
|
||
class Solution { | ||
public String removeStars(String s) { | ||
Stack<Character> st = new Stack<>(); | ||
for(int i=0;i<s.length();i++){ | ||
|
||
if(s.charAt(i)=='*'){ | ||
st.pop(); | ||
} | ||
else{ | ||
st.push(s.charAt(i)); | ||
} | ||
} | ||
StringBuilder sb = new StringBuilder(); | ||
while(!st.isEmpty()){ | ||
sb.append(st.pop()); | ||
} | ||
sb.reverse(); | ||
return sb.toString(); | ||
|
||
|
||
} | ||
|
||
public String removestarsBest(String s){ | ||
int len = s.length(); | ||
byte[] res = new byte[len]; | ||
s.getBytes(0,len,res,0); | ||
int countStars = 0; | ||
for(int i = 0; i<len; i++) | ||
{ | ||
if(res[i] == '*') countStars++; | ||
else res[i-countStars*2] = res[i]; | ||
} | ||
return new String(res, 0, len-countStars*2); | ||
} | ||
|
||
} |