Sponsored
Sponsored
This approach involves maintaining a counter to keep track of the current folder depth. For each log operation, adjust the counter accordingly:
After processing all the logs, the counter will give the minimum operations needed to return to the main folder, as it represents the current depth.
Time Complexity: O(n), where n is the number of logs.
Space Complexity: O(1), no additional space is required except for the depth counter.
1public class Solution {
2 public int minOperations(String[] logs) {
3 int depth = 0;
4 for (String log : logs) {
5 if (log.equals("../")) {
6 if (depth > 0) depth--;
7 } else if (!log.equals("./")) {
8 depth++;
9 }
10 }
11 return depth;
12 }
13
14 public static void main(String[] args) {
15 Solution solution = new Solution();
16 String[] logs = {"d1/", "d2/", "../", "d21/", "./"};
17 System.out.println(solution.minOperations(logs));
18 }
19}
The Java solution uses a loop to traverse the log operations. The depth variable is adjusted based on the log type, keeping track of the current folder depth.
This approach simulates navigating through folders using a stack. The stack keeps track of folder paths:
The stack's size at the end represents the current depth, which is the number of operations needed to return to the main folder.
Time Complexity: O(n).
Space Complexity: O(1).
1using System.Collections.Generic;
public class Solution {
public int MinOperations(string[] logs) {
Stack<string> stack = new Stack<string>();
foreach (string log in logs) {
if (log == "../") {
if (stack.Count > 0) stack.Pop();
} else if (log != "./") {
stack.Push(log);
}
}
return stack.Count;
}
public static void Main(string[] args) {
Solution solution = new Solution();
string[] logs = {"d1/", "d2/", "../", "d21/", "./"};
Console.WriteLine(solution.MinOperations(logs));
}
}
C# uses a Stack object to mimic folder paths, responding to directory operations by manipulating the stack's elements, with the final stack count giving the result.