The 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 ith
step.
The file system starts in the main folder, then the operations in logs
are performed.
Find 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
Approach
Java
public class CrawlerLogFolder {public static void main(String[] args) {String[] logs = { "d1/", "d2/", "../", "d21/", "./" };System.out.println(minOperations(logs));}static int minOperations(String[] logs) {int cnt = 0;for (int i = 0; i < logs.length; i++) {if (logs[i].equals("../")) {if (cnt > 0)cnt--;} else if (logs[i].equals("./"))continue;elsecnt++;}return cnt;}}
C++
#include <bits/stdc++.h>using namespace std;int minOperations(vector<string> &logs){int cnt = 0;for (int i = 0; i < logs.size(); i++){if (logs[i] == "../"){if (cnt > 0)cnt--;}else if (logs[i] == "./")continue;elsecnt++;}return cnt;}int main(){vector<string> logs = {"d1/", "d2/", "../", "d21/", "./"};cout << minOperations(logs);return 0;}
No comments:
Post a Comment