zoukankan      html  css  js  c++  java
  • Simplify Path

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

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

    思路:

    顺序执行,首先循环一开始是找出第一个非/的字符,接下来保存到为/的字符串,

    并判断是否为".",如果是,那就继续continue

    如果是“..”,首先判断堆栈是否有数据,有数据,清除一个数据。

    其他的就是存入这个字符串。在程序结尾处,就是先是添加“/”,再结尾附上字符串。

    代码:

    class Solution {
    public:
        string simplifyPath(string path) {
            int len=path.length();
            int i=0;//代表具体位置
            
            vector<string> result;
            while(i<len){
                //去掉所有的////
                while( path[i]=='/') i++;       //  这个地方不加“ i< len”是没事的,因为开头就已经判断
                if(i==len)    break;
                
                //找出接下来的字符
                string temp;
                while(i<len && path[i]!='/'){   //  这个地方不加“ i< len”不行,因为上面i++可能会导致溢出
                    temp.push_back(path[i++]);
                }
                if(temp==".")   continue;
                if(temp=="..") {
                    if(!result.empty()){
                        result.pop_back();
                    }
                }
                else {
                    result.push_back(temp);
                }
            }
            
            //程序往下执行说明有数据
            string final;
            
            if(result.empty()){
                return "/";
            }
            for(int i=0;i<result.size();i++){
                final.append("/");
                final.append(result[i]);
            }
            return final;
        }
    };


  • 相关阅读:
    MySQL体系结构
    详解MySQL的用户密码过期/锁定解锁功能
    MySQL5.7 密码安全策略
    Python终端如何输出彩色字体
    flashback
    PXC 部署前置检查
    CentOS7 安装docker
    CentOS7 安装ifconfig
    CentOS 7 网络配置
    VMware虚拟机克隆Linux系统引起的网卡问题
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519865.html
Copyright © 2011-2022 走看看