The Leetcode file system keeps a log each time some user performs a change folder operation.
The operations are described below:
"../"
: Move to the parent folder of the current folder. (If you are already in the main folder, remain in the same folder)."./"
: Remain in the same folder."x/"
: Move to the child folder namedx
(This folder is guaranteed to always exist).
You are given a list of strings logs
where logs[i]
is the operation performed by the user at the i<sup>th</sup>
step.
The file system starts in the main folder, then the operations in logs
are performed.
Return the minimum number of operations needed to go back to the main folder after the change folder operations.
LeetCode Problem - 1598
class Solution {
// Method to calculate the minimum number of operations required based on given logs
public int minOperations(String[] logs) {
// Initializing a counter to keep track of the current directory level
int count = 0;
// Iterating through the logs
for(String str : logs){
// If the log represents entering a directory (not ".." or "."), increment the counter
if(!str.startsWith("..") && !str.startsWith(".")) count++;
// If the log represents going up one level ("../"), and the current level is not the root, decrement the counter
else if(str.equals("../") && count!=0) count--;
}
// Return the final counter value representing the minimum number of operations
return count;
}
}