码迷,mamicode.com
首页 > 编程语言 > 详细

Leetcode 之Simplify Path @ python

时间:2015-04-21 22:07:10      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

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

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

使用一个栈来解决问题。遇到‘..‘弹栈,遇到‘.‘不操作,其他情况下压栈。

代码一:

 

class Solution:
    # @param path, a string
    # @return a string
    def simplifyPath(self, path):
        stack = []
        i = 0
        res = ‘‘
        while i< len(path):
            end = i+1
            while end<len(path) and path[end] !="/":
                end += 1
            sub = path[i+1:end]
            if len(sub)>0:
                if sub == "..":
                    if stack !=[]: 
                        stack.pop()
                elif sub != ".":
                    stack.append(sub)
            i = end
                
        if stack == []: 
            return "/"
        for i in stack:
            res += "/"+i
        return res

code 2:

class Solution:
    def simplifyPath(self,path):
        path = path.split(/)
        res = /
        for i in path:
            if i == ..:
                if res != /:
                    res = /.join(res.split(/)[:-1])
                    if res ==‘‘: res = /
            elif i != . and i != ‘‘:
                res += / +i if res != / else i
        return res

 

转自(参考):

1. http://www.cnblogs.com/zuoyuan/p/3777289.html

2. http://blog.csdn.net/linhuanmars/article/details/23972563 

@ JAVA 版本

public String simplifyPath(String path) {
    if(path == null || path.length()==0)
    {
        return "";
    }
    LinkedList<String> stack = new LinkedList<String>();
    StringBuilder res = new StringBuilder();
    int i=0;
    
    while(i<path.length())
    {
        int index = i;
        StringBuilder temp = new StringBuilder();
        while(i<path.length() && path.charAt(i)!=/)
        {
            temp.append(path.charAt(i));
            i++;
        }
        if(index!=i)
        {
            String str = temp.toString();
            if(str.equals(".."))
            {
                if(!stack.isEmpty())
                    stack.pop();
            }
            else if(!str.equals("."))
            {
                stack.push(str);
            }
        }
        i++;
    }
    if(!stack.isEmpty())
    {
        String[] strs = stack.toArray(new String[stack.size()]);
        for(int j=strs.length-1;j>=0;j--)
        {
          res.append("/"+strs[j]);
        }
    }
    if(res.length()==0)
        return "/";
    return res.toString();
}

 

Leetcode 之Simplify Path @ python

标签:

原文地址:http://www.cnblogs.com/jkmiao/p/4445591.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!