My java solution,using stack


  • 0
    L

    public class Solution {
    public String simplifyPath(String path) {
    String[] arr = path.split("/");
    Stack<String> sk = new Stack<String>();
    for(String s : arr){
    if(!s.equals("")){
    if(s.equals("."))
    continue;
    else if(s.equals("..")){
    if(sk.size() >= 1){
    sk.pop();
    }
    else
    continue;
    }
    else{
    sk.push(s);
    }
    }
    }
    Stack<String> sk1 = new Stack<String>();
    if(sk.isEmpty()){
    return "/";
    }
    while(!sk.isEmpty()){
    sk1.push(sk.pop());
    }
    StringBuilder sb = new StringBuilder();
    while(!sk1.isEmpty()){
    sb.append("/").append(sk1.pop());
    }
    return sb.toString();
    }
    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.