|
| 1 | +package string; |
| 2 | + |
| 3 | +import java.util.ArrayDeque; |
| 4 | +import java.util.Deque; |
| 5 | +import java.util.StringTokenizer; |
| 6 | + |
| 7 | +/** |
| 8 | + * Created by gouthamvidyapradhan on 28/07/2017. |
| 9 | + * |
| 10 | + * Given an absolute path for a file (Unix-style), simplify it. |
| 11 | +
|
| 12 | + For example, |
| 13 | + path = "/home/", => "/home" |
| 14 | + path = "/a/./b/../../c/", => "/c" |
| 15 | +
|
| 16 | + Corner Cases: |
| 17 | + Did you consider the case where path = "/../"? |
| 18 | + In this case, you should return "/". |
| 19 | + Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/". |
| 20 | + In this case, you should ignore redundant slashes and return "/home/foo". |
| 21 | + */ |
| 22 | +public class SimplifyPath { |
| 23 | + /** |
| 24 | + * Main method |
| 25 | + * @param args |
| 26 | + * @throws Exception |
| 27 | + */ |
| 28 | + public static void main(String[] args) throws Exception{ |
| 29 | + System.out.println(new SimplifyPath().simplifyPath("/home/")); |
| 30 | + } |
| 31 | + |
| 32 | + public String simplifyPath(String path) { |
| 33 | + if(path == null || path.isEmpty()) return "/"; |
| 34 | + StringTokenizer st = new StringTokenizer(path, "/"); |
| 35 | + Deque<String> dQueue = new ArrayDeque<>(); |
| 36 | + while(st.hasMoreTokens()){ |
| 37 | + String token = st.nextToken(); |
| 38 | + if(token.trim().equals("..")){ |
| 39 | + if(!dQueue.isEmpty()) |
| 40 | + dQueue.pop(); |
| 41 | + } else if(token.trim().equals(".")){ |
| 42 | + //ignore |
| 43 | + } |
| 44 | + else dQueue.push(token); |
| 45 | + } |
| 46 | + if(dQueue.isEmpty()) return "/"; |
| 47 | + StringBuilder finalStr = new StringBuilder(); |
| 48 | + while(!dQueue.isEmpty()){ |
| 49 | + finalStr.append("/").append(dQueue.removeLast()); |
| 50 | + } |
| 51 | + return finalStr.toString(); |
| 52 | + } |
| 53 | + |
| 54 | + |
| 55 | +} |
0 commit comments