|
| 1 | +// https://leetcode.com/problems/simplify-path |
| 2 | +// T: O(|path|) |
| 3 | +// S: O(|path|) |
| 4 | + |
| 5 | +import java.util.LinkedList; |
| 6 | + |
| 7 | +public class SimplifyPath { |
| 8 | + private static final char SLASH = '/'; |
| 9 | + private static final String ROOT = "/"; |
| 10 | + private static final String GO_ONE_LEVEL_UP = ".."; |
| 11 | + private static final String STAY_WHERE_YOU_ARE = "."; |
| 12 | + |
| 13 | + public String simplifyPath(String path) { |
| 14 | + final LinkedList<StringBuilder> fragments = new LinkedList<>(); |
| 15 | + StringBuilder current = new StringBuilder(); |
| 16 | + for (int i = 0 ; i < path.length() ; i++) { |
| 17 | + if (path.charAt(i) == SLASH) { |
| 18 | + if (!isEmpty(current)) { |
| 19 | + addToFragments(current, fragments); |
| 20 | + current = new StringBuilder(); |
| 21 | + } |
| 22 | + } else current.append(path.charAt(i)); |
| 23 | + } |
| 24 | + if (!isEmpty(current)) addToFragments(current, fragments); |
| 25 | + return toPath(fragments); |
| 26 | + } |
| 27 | + |
| 28 | + private String toPath(LinkedList<StringBuilder> fragments) { |
| 29 | + if (fragments.isEmpty()) return ROOT; |
| 30 | + StringBuilder result = new StringBuilder(); |
| 31 | + for (StringBuilder fragment : fragments) { |
| 32 | + result.append(SLASH).append(fragment); |
| 33 | + } |
| 34 | + return result.toString(); |
| 35 | + } |
| 36 | + |
| 37 | + private void removeLast(LinkedList<StringBuilder> fragments) { |
| 38 | + if (!fragments.isEmpty()) { |
| 39 | + fragments.removeLast(); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + private void addToFragments(StringBuilder current, LinkedList<StringBuilder> fragments) { |
| 44 | + String currentString = current.toString(); |
| 45 | + if (GO_ONE_LEVEL_UP.equals(currentString)) { |
| 46 | + removeLast(fragments); |
| 47 | + } else if (!STAY_WHERE_YOU_ARE.equals(currentString)) { |
| 48 | + fragments.add(current); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + private boolean isEmpty(StringBuilder stringBuilder) { |
| 53 | + return stringBuilder.length() == 0; |
| 54 | + } |
| 55 | +} |
0 commit comments