【leetcode】71.(Medium)Simplify Pathes

解题思路:
用一个List(pathes)维护有效路径,遇到有效的路径就加进pathes里面,遇到“. .”先看pathes是否为空,为空就不管,不为空就删掉pathes中的最后一个有效路径。
最后将这个记录了有效路径的List(pathes)转化为String的格式并返回。


提交代码:

class Solution {
    public String simplifyPath(String path) {
      int p1=0,p2=1;
      List<String> pathes=new ArrayList<String>();
      String curPath="";
      
      while(p2<path.length()) {
    	  while(p2<path.length()&&path.charAt(p2)!='/')
    		  p2++;
    	
    	  if(p2==p1+1) {
    		  p1=p2; p2++;continue;
    	  }
    
    	  if(path.substring(p1+1,p2).equals("."))	{
    		  p1=p2; p2++;continue;
    	  }else if(path.substring(p1+1,p2).equals("..")) {
    		  if(pathes.size()!=0)
    			  pathes.remove(pathes.size()-1);
    		  p1=p2; p2++; continue;
    	  }
    	  
    	  pathes.add(path.substring(p1+1, p2));
    	  p1=p2;p2++;
      }

      if(pathes.size()==0)	return "/";
      for(int i=0;i<pathes.size();i++)
    	  curPath+=("/"+pathes.get(i));
    	
    	return curPath;
    }
}

运行结果:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/AXIMI/article/details/84315434