[LeetCode] Simplify Path solution report, leetcodesimplify

Source: Internet
Author: User

[LeetCode] Simplify Path solution report, leetcodesimplify

[Question]

Given an absolute path for a file (Unix-style), simplify it.

For example,
Path ="/home/", =>"/home"
Path ="/a/./b/../../c/", =>"/c"

Click to show corner cases.

Corner Cases:

  • Did you consider the case where path ="/../"?
    In this case, you shoshould return"/".
  • Another corner case is the path might contain multiple slashes'/'Together, such"/home//foo/".
    In this case, you shoshould ignore redundant slashes and return"/home/foo".
[Resolution]

Simplified file paths in Unix, including the removal of excess slashes, the removal of the current directory (./), and replacement of the parent directory.

The Tags given by the question is a stack, but I think it is more convenient to use a queue, so that the simplified directory does not need to be generated backwards.

[Java code]

public class Solution {    public String simplifyPath(String path) {        LinkedList<String> queue = new LinkedList<String>();        String[] names = path.split("/");                for (int i = 0; i < names.length; i++) {            if ("".equals(names[i]) || ".".equals(names[i])) continue;                        if ("..".equals(names[i])) {                if (!queue.isEmpty()) {                    queue.pollLast();                }            } else {                queue.add(names[i]);            }        }                StringBuilder newPath = new StringBuilder();        while (!queue.isEmpty()) {            newPath.append("/");            newPath.append(queue.pollFirst());        }                if (newPath.length() == 0) return "/";                return newPath.toString();    }}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.