71. Simplify Path

来源:互联网 发布:icloud优化存储空间 编辑:程序博客网 时间:2024/06/07 18:03

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 should return "/".
  • Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
    In this case, you should ignore redundant slashes and return "/home/foo".

1.注意使用正则表达式进行分隔

2.注意分隔后的数组  存在“”的情况 需要处理

3.熟悉switch的用法

switch(x){

case"xxx":  break;/continue;

}

4.ArrayList<>()   数组列表





public class Solution {    public String simplifyPath(String path) {        String []s=path.split("\\/+");        ArrayList<String> st=new ArrayList<>();        for(String c:s){            switch(c){                case"":                case".": continue;                case"..":                    if(st.size()>0)                        st.remove(st.size()-1);                        break;                default:                        st.add(c);                    break;            }        }        if(st.size()==0)            return "/";        StringBuilder sb = new StringBuilder();        for(String sd : st){            sb.append("/");            sb.append(sd);        }        return sb.toString();    }}


0 0
原创粉丝点击