You are given a string s, which contains stars *.
In one operation, you can:
Return the string after all stars have been removed.
Note:
Input: s = “leet**cod*e”
Output: “lecoe”
Explanation: Performing the removals from left to right:
Input: s = “erase*****”
Output: “”
Explanation: The entire string is removed, so we return an empty string.
From: LeetCode
Link: 2390. Removing Stars From a String
Initialize a Stack: A character array (acting as a stack) is created to temporarily store characters from the input string.
Process the Input String: Iterate through each character of the input string s.
Form the Resultant String: After processing all characters of s, the stack contains the resultant string, but in reverse order. The characters in the stack are then copied into a new string called result, which represents the final string after all removals.
Memory Management: Dynamic memory allocation is used for the stack and the result string. It’s important to allocate enough memory to accommodate all characters and the null terminator. After copying the required characters to the result, the memory used by the stack is freed to prevent memory leaks.
Return the Result: Finally, the function returns the result string, which is the modified version of the input string after performing all the specified operations.
char* removeStars(char* s) {
int n = strlen(s); // Length of the input string
char* stack = (char*)malloc((n + 1) * sizeof(char)); // Allocate memory for the stack, +1 for null terminator
int top = -1; // Top of the stack
// Traverse the input string
for (int i = 0; i < n; i++) {
if (s[i] != '*') {
// Push non-star characters onto the stack
stack[++top] = s[i];
} else if (top != -1) {
// Pop the top character for a star
top--;
}
}
// Add a null terminator at the end of the stack content
stack[top + 1] = '\0';
// Create the result string with exact size
char* result = (char*)malloc((strlen(stack) + 1) * sizeof(char)); // Allocate memory for the result based on stack's current length
for (int i = 0; i <= top; i++) {
result[i] = stack[i]; // Manually copy the characters
}
result[top + 1] = '\0'; // Add null terminator to the result
free(stack); // Free the stack memory
return result; // Return the result
}