Algorithm leetcode|71. Simplify the path (rust punches hard)



71. Simplify the path:

You are given a string pathrepresenting a Unix-style absolute path (beginning with '/') pointing to a certain file or directory, please convert it into a more concise canonical path.

In Unix-style filesystems, a single dot ( .) indicates the current directory itself; additionally, two dots ( ..) indicate switching a directory one level up (pointing to a parent directory); both can be part of complex relative paths. Any number of consecutive slashes (ie, '//') is treated as a single slash '/'. For this question, dots in any other format (for example, '...') are treated as file/directory names.

Note that the returned canonical path MUST follow the format below:

  • Always '/'start with a slash.
  • There must be exactly one slash between two directory names '/'.
  • The last directory name (if present) cannot end with '/'.
  • Also, path only includes directories on the path from the root directory to the target file or directory (that is, without '.'the or '..').

Returns the simplified canonical path .

Example 1:

输入:
	
	path = "/home/"
	
输出:
	
	"/home"
	
解释:
	
	注意,最后一个目录名后面没有斜杠。 

Example 2:

输入:
	
	path = "/../"
	
输出:
	
	"/"
	
解释:
	
	从根目录向上一级是不可行的,因为根目录是你可以到达的最高级。

Example 3:

输入:
	
	path = "/home//foo/"
	
输出:
	
	"/home/foo"
	
解释:
	
	在规范路径中,多个连续斜杠需要用一个斜杠替换。

Example 4:

输入:
	
	path = "/a/./b/../../c/"
	
输出:
	
	"/c"

hint:

  • 1 <= path.length <= 3000
  • pathIt consists of English letters, numbers, '.', '/'or '_'.
  • pathis a valid Unix-style absolute path.

analyze:

  • Facing this algorithm problem, the second leader fell into deep thought again.
  • Just simulate directly, the key is to choose the right data structure, it will be easy to solve.
  • Split the complete path into groups according to '/', use the stack to store the simplified path structure, and follow the branch logic according to the situation:
    1. If it is '.'or 空格: '空格'it has no meaning, '.'it means the current directory, and it will be skipped directly without processing.
    2. If it is '..': it means to jump to the upper-level directory. At this time, as long as the root directory is not reached, it must jump up, so as long as the stack is not empty, the stack operation will be performed.
    3. Other character strings: they are all regarded as valid directory names and pushed into the stack.
  • After the traversal process is completed, the simplified paths are spliced ​​according to the queue method.

answer:

rust:

impl Solution {
    
    
    pub fn simplify_path(path: String) -> String {
    
    
        let mut stack = Vec::new();
        path.split('/').for_each(|name| match name {
    
    
            "." | "" => (),
            ".." => {
    
    
                stack.pop();
            }
            _ => stack.push(name),
        });
        "/".to_string() + &stack.join("/")
    }
}

go:

func simplifyPath(path string) string {
    
    
    var stack []string
	for _, name := range strings.Split(path, "/") {
    
    
		if name == ".." {
    
    
			if len(stack) > 0 {
    
    
				stack = stack[:len(stack)-1]
			}
		} else if name != "" && name != "." {
    
    
			stack = append(stack, name)
		}
	}
	return "/" + strings.Join(stack, "/")
}

c++:

class Solution {
    
    
public:
    string simplifyPath(string path) {
    
    
        stringstream ss(path);
        vector<string> stack;
        string name = "";
        while (getline(ss, name, '/')) {
    
    
            if (name == "..") {
    
    
                if (!stack.empty()) {
    
    
                    stack.pop_back();
                }
            } else if (!name.empty() && name != ".") {
    
    
                stack.push_back(move(name));
            }
        }
        string ans;
        if (stack.empty()) {
    
    
            ans = "/";
        } else {
    
    
            for (string &name: stack) {
    
    
                ans += "/" + move(name);
            }
        }
        return ans;
    }
};

python:

class Solution:
    def simplifyPath(self, path: str) -> str:
        names = path.split("/")
        stack = list()
        for name in names:
            if name == "..":
                if stack:
                    stack.pop()
            elif name and name != ".":
                stack.append(name)
        return "/" + "/".join(stack)


java:

class Solution {
    
    
    public String simplifyPath(String path) {
    
    
        String[]      names = path.split("/");
        Deque<String> stack = new ArrayDeque<String>();
        for (String name : names) {
    
    
            if ("..".equals(name)) {
    
    
                if (!stack.isEmpty()) {
    
    
                    stack.pollLast();
                }
            } else if (name.length() > 0 && !".".equals(name)) {
    
    
                stack.offerLast(name);
            }
        }
        StringBuilder ans = new StringBuilder();
        if (stack.isEmpty()) {
    
    
            ans.append('/');
        } else {
    
    
            while (!stack.isEmpty()) {
    
    
                ans.append('/');
                ans.append(stack.pollFirst());
            }
        }
        return ans.toString();
    }
}

Thank you very much for reading this article~
Welcome to 【Like】【Favorite】【Comment】Walk three times in a row~ It
is not difficult to give up, but it must be cool to persevere~
I hope we all can improve a little every day~
This article is written by the white hat of the second master: https://le-yi.blog.csdn.net/Blog original~


Guess you like

Origin blog.csdn.net/leyi520/article/details/132356719