当前位置:网站首页>LeetCode 1598. Folder operation log collector

LeetCode 1598. Folder operation log collector

2022-07-06 00:09:00 Daylight629

1598. Folder operations log collector

Whenever a user performs a change folder operation ,LeetCode The file system keeps a log record .

The following is a description of the change operation :

  • "../" : Move to the parent folder of the current folder . If it is already in the home folder , be Continue to stay in the current folder .
  • "./" : Continue to stay in the current folder **.**
  • "x/" : Move to a place called x In subfolders of . Subject data The folder always exists x .

Here's a list of strings logs , among logs[i] It's the user ith What to do next .

The file system starts in the home folder , And then execute logs The operation .

After all folder changes have been performed , Please find out The minimum number of steps required to return to the home folder .

Example 1:

img

 Input :logs = ["d1/","d2/","../","d21/","./"]
 Output :2
 explain : perform  "../"  Operation change folder  2  Time , You can go back to your home folder 

Example 2:

img

 Input :logs = ["d1/","d2/","./","d3/","../","d31/"]
 Output :3

Example 3:

 Input :logs = ["d1/","../","../","../"]
 Output :0

Tips :

  • 1 <= logs.length <= 103
  • 2 <= logs[i].length <= 10
  • logs[i] Contains lowercase English letters , Numbers ,'.' and '/'
  • logs[i] Conform to the format described in the statement
  • The folder name consists of lowercase English letters and numbers

Two 、 Method 1

class Solution {
    
    public int minOperations(String[] logs) {
    
        int ans = 0;
        for (String log : logs) {
    
            if (log.charAt(0) != '.') ans++;
            else if (ans != 0 && log.equals("../")) ans--;
        }
        return ans;
    }
}

Complexity analysis

  • Time complexity :O(n).

  • Spatial complexity :O(1).

原网站

版权声明
本文为[Daylight629]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140240528336.html