Last active
August 29, 2015 14:10
-
-
Save h2rashee/363368b51e1522ebe71a to your computer and use it in GitHub Desktop.
Use absolute and relative path to get the resulting path
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Write a function (in a non-scripting language) to give the absolute path | |
given the current working directory and a path. e.g. | |
CWD: “/home/h2rashee/downloads/” | |
path: “../../hello.c” | |
result: “/home/hello.c” | |
CWD: “” | |
path: “../hello.c” | |
result: “../hello.c” | |
*/ | |
import java.util.*; | |
class DirectoryMap | |
{ | |
static Stack<String> path; | |
// MAIN function | |
public static void main(String[] args) { | |
path = new Stack<String>(); | |
// READ input | |
Scanner sc = new Scanner(System.in); | |
String cwd = sc.nextLine(); | |
String newPath = sc.nextLine(); | |
System.out.println(getPath(cwd, newPath)); | |
} | |
// Traverse a directory path given an absolute path | |
// and a relative path to get to | |
static String getPath(String cwd, String relPath) { | |
StringTokenizer cwdSt = new StringTokenizer(cwd, "/"); | |
StringTokenizer pathSt = new StringTokenizer(relPath, "/"); | |
// Load current path into the stack | |
while(cwdSt.hasMoreTokens()) { | |
path.push(cwdSt.nextToken()); | |
} | |
// Traverse the file directory | |
while(pathSt.hasMoreTokens()) { | |
String nextStep = pathSt.nextToken(); | |
// When it is a step-back, | |
if(nextStep.equals("..")) { | |
// we may not want to dial back | |
if(path.empty()) { | |
// but want to preserve the directory sequence | |
path.push(nextStep); | |
} else { | |
// otherwise cd .. | |
path.pop(); | |
} | |
} else { | |
// cd <nextStep> | |
path.push(nextStep); | |
} | |
} | |
String newPath = concatPath(path); | |
// We have a non-absolute path | |
if(newPath.contains("..")) { | |
// so we omit the leading / | |
return newPath.substring(1); | |
} | |
return newPath; | |
} | |
// Concatenate a stack with a file path into a well-formed string | |
static String concatPath(Stack<String> path) { | |
while(!path.empty()) { | |
String elem = path.pop(); | |
return concatPath(path) + "/" + elem; | |
} | |
return ""; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment