Yelp Interview Question
Country: United States
Interview Type: In-Person
We can use a stack for this problem.
Step 1: If destination doesn't start with root, enter source directories to stack
Step 2: Split source and destination around match of regular expression "/" and put each of them in array.
Step 3: If a ".." pattern is found, pop the last added directory from array, otherwise push it to array.
Step 4: to get the end directory, look at the topmost element of the array
package career.cup.yelp;
import java.util.ArrayList;
import java.util.Stack;
public class getDirectory {
public static void main(String args[]){
getDirectiry("/logs", "test/nodes/../modules/logs");
getDirectiry("/logs", "test/nodes/../modules/logs/..");
}
public static void getDirectiry(String src, String destination){
Stack<String> directoryStack = new Stack<String>();
String[] listDestination = destination.split("/");
String[] listHost = src.split("/");
if(!destination.startsWith("/")){
for(String str : listHost){
if(!(str.matches(".."))){
directoryStack.push(str);
}
else if((str.matches(".."))){
directoryStack.pop();
}
}
}
for(String str : listDestination){
if(!(str.matches(".."))){
directoryStack.push(str);
}
else if((str.matches(".."))){
directoryStack.pop();
}
}
System.out.println(directoryStack);
}
}
import java.util.*;
public class cdImplementation
{
public static void main(String args[])
{
//('a/b','c/../d/e/..f')
String input[] = new String[]{"a/b","c/../d/e/../f"};
Stack<String> stack = new Stack<String>();
String str = "";
for (String word : input)
for (String i : word.split("/"))
{
if (!i.equals(".."))
stack.push(i);
else
stack.pop();
}
while (!stack.isEmpty())
{
str = stack.pop() + "/" + str ;
}
System.out.println(str);
}
}
-Firstly we take a/b in a string called currentdirectory
-Then we split "c/../d/e/../f" with delimiter as "/"
-When there is a ".." then we take a substring of the currentdirectory
-If there is a character, then we will append "/" and the character
- dhirajb1989 May 14, 2014