Menu Close

Program to Crawler Log Folder

Here, we will see Program to Crawler Log Folder with code and algorithm.

The techieindoor 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 root folder, then the operations in logs are performed.

Return the minimum number of operations needed to go back to the root folder after the change folder operations.

Example:

Input: logs = ["d1/","d2/","../","d21/","./"]
Output: 2
Explanation: Use this change folder operation "../" 2 times and go back to the main folder.

Program to Crawler Log Folder code in C++

Code 1:

#include <iostream>
#include <vector>

using namespace std;

int minOperations(vector<string>& logs) {
    int depth = 0;
        
    for(auto &it : logs) {
        // "../" - Return from child to parent foler
        if(it == "../") {
            if(depth > 0) {
                depth -= 1;
            }
        } else if(it == "./") {
            // "./" - Stay on the current path
            continue;
        } else
            depth++;
    }
    return depth;
}
    
int main()
{
    
    vector<string> logs = {"d1/","d2/","../","d21/","./"};
    cout<<minOperations(logs);

    return 0;
}

Code 2:

#include <iostream>
#include <vector>

using namespace std;

int minOperations(vector<string>& logs) {
    int depth = 0;
        
    for (const auto& op: logs)
        if (op[0] != '.') ++depth;
        else if (op[1] == '.' && depth > 0) --depth;
    
    return depth;
}
    
int main()
{
    
    vector<string> logs = {"d1/","d2/","../","d21/","./"};
    cout<<minOperations(logs);

    return 0;
}

Code 3:

#include <iostream>
#include <vector>
#include <stack>

using namespace std;

int minOperations(vector<string>& logs) {
    stack<string>stk;
    for(int i = 0 ; i <logs.size();i++)
    {
        string str = logs[i];
        if(str == "../")
        {
            if(!stk.empty())
            {
                stk.pop();
            }
        }
        else if(str != "./")
        {
            stk.push(str);
        }
    }
    return stk.size();
    }
    
int main()
{
    
    vector<string> logs = {"d1/","d2/","../","d21/","./"};
    cout<<minOperations(logs);

    return 0;
}

Output:

2

To check more leetcode problem’s solution. Pls click given below link:

https://techieindoor.com/category/leetcode/

Posted in C++, Easy

Leave a Reply

Your email address will not be published. Required fields are marked *