LeetCode 3170: Lexicographically Minimum String After Removing Stars Solution
Master LeetCode problem 3170 (Lexicographically Minimum String After Removing Stars), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3170. Lexicographically Minimum String After Removing Stars
Problem Explanation
Explanation
To solve this problem, we can use a stack to keep track of the characters in the input string. We iterate through the input string, and for each character:
- If it is not a '*', we push it onto the stack.
- If it is a '', we pop the top element from the stack (which is the smallest non-'' character encountered so far) and skip the current '*' character.
After iterating through the string, we reconstruct the final string by popping the remaining characters from the stack.
Algorithm:
- Initialize an empty stack.
- Iterate through each character in the input string:
- If the character is not '*', push it onto the stack.
- If the character is '*', pop the top element from the stack.
- Reconstruct the final string by popping the remaining characters from the stack in reverse order.
Time Complexity: O(n), where n is the length of the input string. Space Complexity: O(n), where n is the length of the input string.
Solution Code
class Solution {
public String minString(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c != '*') {
stack.push(c);
} else if (!stack.isEmpty()) {
stack.pop();
}
}
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()) {
sb.insert(0, stack.pop());
}
return sb.toString();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3170 (Lexicographically Minimum String After Removing Stars)?
This page provides optimized solutions for LeetCode problem 3170 (Lexicographically Minimum String After Removing Stars) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3170 (Lexicographically Minimum String After Removing Stars)?
The time complexity for LeetCode 3170 (Lexicographically Minimum String After Removing Stars) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3170 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3170 in Java, C++, or Python.