1598. Crawler Log Folder #291
-
Topics: The Leetcode file system keeps a log each time some user performs a change folder operation. The operations are described below:
You are given a list of strings The file system starts in the main folder, then the operations in Return the minimum number of operations needed to go back to the main folder after the change folder operations. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine the minimum number of operations required to return to the main folder after performing a series of change folder operations. The operations can be moving to a parent folder, staying in the current folder, or moving to a child folder. The solution involves simulating these operations while keeping track of the current depth from the main folder. Approach
Let's implement this solution in PHP: 1598. Crawler Log Folder <?php
/**
* @param String[] $logs
* @return Integer
*/
function minOperations($logs) {
$depth = 0;
foreach ($logs as $log) {
if ($log == "../") {
if ($depth > 0) {
$depth--;
}
} elseif ($log != "./") {
$depth++;
}
}
return $depth;
}
// Test cases
$logs1 = array("d1/", "d2/", "../", "d21/", "./");
$logs2 = array("d1/", "d2/", "./", "d3/", "../", "d31/");
$logs3 = array("d1/", "../", "../", "../");
echo minOperations($logs1) . "\n"; // Output: 2
echo minOperations($logs2) . "\n"; // Output: 3
echo minOperations($logs3) . "\n"; // Output: 0
?> Explanation:
This approach efficiently tracks the current folder depth by processing each operation in sequence, ensuring optimal performance with a linear pass through the logs array. The solution handles edge cases such as staying at the main folder when encountering "../" operations at depth 0. |
Beta Was this translation helpful? Give feedback.
We need to determine the minimum number of operations required to return to the main folder after performing a series of change folder operations. The operations can be moving to a parent folder, staying in the current folder, or moving to a child folder. The solution involves simulating these operations while keeping track of the current depth from the main folder.
Approach