LeetCode -- Simplify Path

Source: Internet
Author: User

LeetCode -- Simplify Path
Description:


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


For example,
Path =/home/, =>/home
Path =/a/./B/.../../c/, =>/c




Is to simplify a UNIX-style path.


Ideas:
1. Separate the path with '/' in the array and filter out elements with a value of.,/or null.
2. Use the stack when traversing the array. If the value is..., if the stack has elements, it will pop up. If the value is not.
3. Finally, we can traverse and spell the simplified path of the stack.


Implementation Code:




public class Solution {    public string SimplifyPath(string path) {        var folders = path.Split('/').Where(x=>x!=. && x != / && x != ).ToList();    var stack = new Stack
 
  ();    for(var i = 0;i < folders.Count; i++){    if(folders[i] == ..){    if(stack.Count > 0){    stack.Pop();    }        }    else{    stack.Push(folders[i]);    }    }        var result = string.Empty;    while(stack.Count > 0){    var f = stack.Pop();    result = string.Format(/{0},f) + result;    }    if(result == string.Empty){    return /;    }        return result;    }}
 


 

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.