https://leetcode.com/problems/longest-absolute-file-path/ public class Solution { public int lengthLongestPath(String input) { Stack<Integer> stk = new Stack<Integer>(); int left = 0; int curStrlen = 0; int curTab = 0; int ret = 0; boolean hasDot = false; boolean isFile = false; for (int i=0; i<input.length(); i++) { // \n if (input.charAt(i) == 10) { curStrlen = i-left; if (!stk.empty()) { curStrlen += 1 + stk.peek(); } if (isFile && curStrlen > ret) { ret = curStrlen; } stk.push(curStrlen); hasDot = false; isFile = false; curTab = 0; left = -1; } // \t else if (input.charAt(i) == 9 && curTab < stk.size()) { curTab++; } else if (input.charAt(i) == ‘ ‘ && i+3 < input.length() && input.substring(i, i+4).equals(" ") && curTab < stk.size()) { curTab++; i += 3; } else { if (left == -1) { int stkLen = stk.size(); for (int j=0; j<stkLen-curTab; j++) { stk.pop(); } left = i; } if (input.charAt(i) == ‘.‘) { hasDot = true; } else { if (hasDot) { isFile = true; } } } } curStrlen = input.length()-left; if (!stk.empty()) { curStrlen += 1 + stk.peek(); } if (isFile && curStrlen > ret) { ret = curStrlen; } return ret; } }
时间: 2024-10-03 23:28:57