Problem Description
Explanation
To solve this problem, we can simulate the operations described in the logs and keep track of the current folder. We can use a stack data structure to represent the current directory structure. If we encounter "../", we pop from the stack to move to the parent folder. If we encounter "./", we stay in the same folder. If we encounter a folder name, we push it onto the stack to move to the child folder.
Algorithm
- Initialize an empty stack to represent the current directory structure.
- Iterate through each operation in the logs.
- If the operation is "../", pop from the stack if it's not empty (to move to the parent folder).
- If the operation is "./", do nothing (stay in the same folder).
- If the operation is a folder name, push it onto the stack (to move to the child folder).
- Finally, return the size of the stack (the number of operations needed to go back to the main folder).
Time Complexity
The time complexity of this algorithm is O(n) where n is the number of operations in the logs.
Space Complexity
The space complexity of this algorithm is O(n) where n is the number of operations in the logs.
Solutions
class Solution {
public int minOperations(String[] logs) {
Stack<String> stack = new Stack<>();
for (String log : logs) {
if (log.equals("../")) {
if (!stack.isEmpty()) {
stack.pop();
}
} else if (!log.equals("./")) {
stack.push(log);
}
}
return stack.size();
}
}
Loading editor...