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 named x (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 ith 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.
Example 1:
Input: logs = ["d1/","d2/","../","d21/","./"]
Output: 2
Explanation: Use this change folder operation "../" 2 times and go back to the main folder.
Example 2:
Input: logs = ["d1/","d2/","./","d3/","../","d31/"]
Output: 3
Example 3:
Input: logs = ["d1/","../","../","../"]
Output: 0
Constraints:
1 <= logs.length <= 10^3
2 <= logs[i].length <= 10
logs[i]
contains lowercase English letters, digits,'.'
, and'/'
.logs[i]
follows the format described in the statement.- Folder names consist of lowercase English letters and digits.
You are given a list of command/logs of navigating through folders. We need to find the minimum number of operations needed to go back to the main folder after the change folder operations.
There are three types of operations in the logs:
"../"
move to parent folder of current folder"./"
stay on the same folder- And
"x/"
move down to ax
sub folder.
As the second command does not add any value (there is no location change), we can ignore this one.
Third command move down to a sub folder and hence we need additional operations to go back to the Main
. First command move upwards and hence reduce the operation needed to go back to the Main
.
- Declare
operationNeeded
= 0; - for each
log
in thelogs
:- if
log
is equal to"../"
- if
operationNeeded
is greater than 0 (not on theMain
folder)- Reduce required
operationNeeded
by one.
- Reduce required
- else do nothing
- if
- else if
log
is not equal to"./"
(i,e.log
equal to"x/"
)- Increase required
operationNeeded
by one.
- Increase required
- if
- Return
operationNeeded
Input: logs = ["d1/","d1/","../","d21/","./"]
Output: 2
log | operationNeeded |
---|---|
"d1/" |
1 |
"d1/" |
2 |
"../" |
1 |
"d21/" |
2 |
"./" |
2 |
minimum number of operations needed = 2
.
-
Time Complexity:
O(n)
wheren
= size of thelogs
-
Space Complexity:
O(1)
class Solution {
public:
int minOperations(vector<string>& logs) {
int operationNeeded = 0;
for(string log:logs) {
if(log == "../") {
if(operationNeeded > 0) {
operationNeeded--;
}
} else if(log != "./") {
operationNeeded++;
}
}
return operationNeeded;
}
};
Tags: C++, cpp, leetcode, leetcode 1598, Greedy, Implementation