Topic:
Given an absolute path for a file (Unix-style), simplify it.
For example,
Path="/home/", ="/home"
Path="/a/./b/../../c/", ="/c"
Exercises
Problem-solving ideas: The problem is to simplify the table of contents, each level of the directory is preceded by a slash, I can first split the slash, the result is divided into 4 different cases: Normal directory name, null character, ".", "...". For "." and null characters we ignore it, for the normal directory name we press directly into the stack, for "..", we put the stack top element out of the stack. After these processing, if the stack is empty we return to the root directory, if the stack is not empty we will step out of the stack and precede each element with a slash, the first out of the path is the last side.
Code:
Import Java.sql.array;import Java.util.stack;public class Leetcode71_simplifypath {/** * @param args */public static void Main (string[] args) {//TODO auto-generated method stubstring input= "/a/./b/. /.. /c/"; SYSTEM.OUT.PRINTLN (Simplifypath (input));} public static string Simplifypath (string path) {string[] Patharray=path.split ("/"); int length=patharray.length; stack< string> stack=new stack<> (); String result= ""; for (int i=0;i<length;i++) {if (Patharray[i].equals ("") | | Patharray[i].equals (".")) {}else if (patharray[i].equals (".")) {if (!stack.isempty ()) {Stack.pop ();}} else {Stack.push (patharray[i]);}} if (Stack.isempty ()) return "/"; while (!stack.isempty ()) {result= "/" +stack.pop () +result;} return result;} }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
LeetCode71 Simplify Path Java