当前位置: 首页 > 工具软件 > simplify > 使用案例 >

Simplify Path(LeetCode)

邵文乐
2023-12-01

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

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

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".


public class Solution {
    public String simplifyPath(String path) {
		String[] strArray = path.split("/");
		List<String> list = new ArrayList<String>();
		
		for(int i = 0;i < strArray.length;i++){
			if(strArray[i].equals(".."))
			{
				if(!list.isEmpty())
					list.remove(list.size()-1);
				continue;
			}
			else if(strArray[i].equals(".") || strArray[i].equals(""))
				continue;
			list.add(strArray[i]);
		}
		
		if(list.isEmpty())
			return "/";
		
		StringBuilder sb = new StringBuilder();
		for(Iterator<String> iterator = list.iterator();iterator.hasNext();){
			sb.append("/"+iterator.next());
		}
		return sb.toString();
    }
}


 类似资料: