zoukankan      html  css  js  c++  java
  • LeetCode OJ:Simplify Path(简化路径)

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

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

    简化路径,linux下面简单的路径操作而已,代码如下:

     1 class Solution {
     2 public:
     3     string simplifyPath(string path) {
     4         stack<string> tokenStk;
     5         int sz = path.size();
     6         for (int i = 0; i < sz; ++i){
     7             if (path[i] == '/') continue;
     8             else{
     9                 string tmp = "";
    10                 for (int j = i; j < sz && path[j] != '/'; ++j, ++i){
    11                     tmp.append(1, path[i]);
    12                 }
    13                 if (tmp == ".."){
    14                     if (!tokenStk.empty())tokenStk.pop();
    15                 }
    16                 else if (tmp == ".")
    17                     continue;
    18                 else
    19                     tokenStk.push(tmp);
    20             }
    21         }
    22 
    23         vector<string> tokenVec;
    24         while (!tokenStk.empty()){//存储的是反向的目录,将其输出打vector中,这样比较好
    25             tokenVec.push_back(tokenStk.top());
    26             tokenStk.pop();
    27         }
    28         string ret;
    29         if (tokenVec.empty()) ret.append(1, '/');
    30         for (int i = tokenVec.size() - 1; i >= 0; --i){
    31             ret.append(1, '/');
    32             ret.append(tokenVec[i]);
    33         }
    34         return  ret;
    35     }
    36 };

     PS:应为短的if不喜欢加上{}的原因,找bug找了好久,下次不能继续这个坏习惯,mark一下。

    下面是java版本,不得不说java的String的api比c++的要好用太多了,可以用正则表达式分割单词真是爽啊,不用向c++那样做很多次判断了,代码如所示:

     1 public class Solution {
     2     public String simplifyPath(String path) {
     3         String[] pathArr = path.split("[//]+");//首先用正则表达式将整个式子按照//分开
     4         Stack<String> s = new Stack<String>();
     5         for(int i = 0; i < pathArr.length; ++i){
     6             if(pathArr[i].equals("..")){
     7                 if(!s.isEmpty())
     8                     s.pop();
     9             }else if(pathArr[i].equals(".")){
    10                 continue;
    11             }else{
    12                 if(!pathArr[i].equals(""))//split有可能会分割出来空白的字符,这里应该注意并且剔除
    13                     s.push(pathArr[i]);
    14             }
    15         }
    16         String ret = new String("");
    17         while(!s.isEmpty()){
    18             ret = "/" + s.pop() + ret;
    19         }
    20         if(ret.length() == 0)
    21             ret += "/";
    22         return ret;
    23     }
    24 }
  • 相关阅读:
    hadoopnamenode配置及问题处理方案
    hadoop 运行 Java程序
    hadoop命令大全
    DOS
    腾讯Linux QQ安装
    linux下安装realplayer
    在linux中配置安装telnet服务
    关于C#静态构造函数的几点说明
    linux下的Network File Server共享配置
    Oracle学习笔记
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4886529.html
Copyright © 2011-2022 走看看