|
| 1 | +package com.wdbyte.leetcode; |
| 2 | + |
| 3 | +import java.util.Stack; |
| 4 | + |
| 5 | +/** |
| 6 | + * 388. 文件的最长绝对路径 |
| 7 | + * https://leetcode-cn.com/problems/longest-absolute-file-path/ |
| 8 | + * |
| 9 | + * @author niulang |
| 10 | + * @date 2022/04/20 |
| 11 | + */ |
| 12 | +public class LeetCode388 { |
| 13 | + public static void main(String[] args) { |
| 14 | + LeetCode388 leetCode388 = new LeetCode388(); |
| 15 | + //int path = leetCode388.lengthLongestPath2("dir\n file.txt"); |
| 16 | + int path = leetCode388.lengthLongestPath2("dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext"); |
| 17 | + System.out.println(path); |
| 18 | + } |
| 19 | + |
| 20 | + public int lengthLongestPath(String input) { |
| 21 | + String[] array = input.split("\n"); |
| 22 | + Stack<String> stack = new Stack(); |
| 23 | + int lastTCount = 0; |
| 24 | + int maxSize = 0; |
| 25 | + for (String path : array) { |
| 26 | + int tCount = 0; |
| 27 | + while (path.contains("\t")) { |
| 28 | + tCount++; |
| 29 | + path = path.substring(path.indexOf("\t") + 1); |
| 30 | + } |
| 31 | + if (tCount > lastTCount) { |
| 32 | + stack.push(path); |
| 33 | + } else { |
| 34 | + for (int i = 0; i <= (lastTCount - tCount); i++) { |
| 35 | + if (!stack.isEmpty()) { |
| 36 | + stack.pop(); |
| 37 | + } |
| 38 | + } |
| 39 | + stack.push(path); |
| 40 | + } |
| 41 | + lastTCount = tCount; |
| 42 | + if (path.contains(".")) { |
| 43 | + int size = 0; |
| 44 | + for (String s : stack) { |
| 45 | + size += s.length(); |
| 46 | + } |
| 47 | + size = size + stack.size() - 1; |
| 48 | + if (size > maxSize) { |
| 49 | + maxSize = size; |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + return maxSize; |
| 54 | + } |
| 55 | + |
| 56 | + public int lengthLongestPath2(String input) { |
| 57 | + String[] array = input.split("\n"); |
| 58 | + Stack<Integer> stack = new Stack(); |
| 59 | + int lastTCount = 0; |
| 60 | + int maxSize = 0; |
| 61 | + for (String path : array) { |
| 62 | + int tCount = 0; |
| 63 | + while (path.contains("\t")) { |
| 64 | + tCount++; |
| 65 | + path = path.substring(path.indexOf("\t") + 1); |
| 66 | + } |
| 67 | + if (tCount > lastTCount) { |
| 68 | + stack.push(path.length()); |
| 69 | + } else { |
| 70 | + for (int i = 0; i <= (lastTCount - tCount); i++) { |
| 71 | + if (!stack.isEmpty()) { |
| 72 | + stack.pop(); |
| 73 | + } |
| 74 | + } |
| 75 | + stack.push(path.length()); |
| 76 | + } |
| 77 | + lastTCount = tCount; |
| 78 | + if (path.contains(".")) { |
| 79 | + int size = 0; |
| 80 | + for (Integer s : stack) { |
| 81 | + size += s; |
| 82 | + } |
| 83 | + size = size + stack.size() - 1; |
| 84 | + if (size > maxSize) { |
| 85 | + maxSize = size; |
| 86 | + } |
| 87 | + } |
| 88 | + } |
| 89 | + return maxSize; |
| 90 | + } |
| 91 | + |
| 92 | +} |
0 commit comments