Feature #5: Recover Files
Implementing the "Recover Files" feature for our "Operating System" project.
We'll cover the following...
Description
A file contains a byte stream and some optional sections. These optional sections are identified by start and end delimiters. While downloading a file, some delimiters may get corrupted. This means that the starting delimiter may get replaced by an ending delimiter and vice versa. We cannot find which delimiter has been corrupted. Therefore, we need to remove the unmatched delimiters from the file to recover the file.
In this feature, we will make a tool to recover corrupted files by removing the minimum number of unmatched start or end delimiters.
Note: A file can contain nested delimiters.
We will be provided with a string that represents a file. Let’s look at a sample of this:
Let’s take a look at the edge cases:
Solution
We will have to traverse the array to:
- Check whether a delimiter is unmatched or not.
- Note the index of the unmatched delimiter, so that we can remove it later on.
To do this, we will go over each character one by one. If the character is a delimiter, we will push it and its index in the stack. Otherwise, we will move on to the next character. To check whether the delimiter is matched or not, we will make the following check at each character: if the current character is an ending delimiter and the character at the top of the stack is a starting one, then both of them are matched. In such a case, we will not add the current character to the stack, and we will pop an element from the stack to remove the starting delimiter. This way, we will not have any matched delimiter in the stack.
Now, we will make a new string and start appending characters from the end of the original string in ...