算法设计与分析HW8:LeetCode71.Simplify Path

Description:

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


Note:

For example,

path = "/home/", => "/home"

path = "/a/./b/../../c/", => "/c"


Solution:

  Analysis and Thinking:

问题要求对输入的文件的绝对路径进行简化,并输出简化的路径结果。观察发现这是unix风格的文件路径命名,其重点是对字符串的处理,特别对“..”这一表示上级目录的符号的处理,本文利用了栈结构来处理,用栈来记录文件路径名,并对处理到的字符串是/或.或..或其他字符,做相应的处理。

  

  Steps:

1.构建栈用于记录输入的文件路径名

2.遍历路径名,如果当前字符是'/',则不处理,跳至下一个字符

3.如果不是/,用一变量s存储字符子串,知道下一个'/'的出现

4.判断s是否为“..”,如果是,且当前路径栈不为空,则弹栈

5.如果s不为“”、“.”、".."三者之一,则将其入栈,如果文件路径还没遍历完,跳回2

6.将栈内元素弹出,并用一结果数组记录链接,返回结果数组


  

Codes:

 class Solution
 {
 public:
    string simplifyPath(string path)
    {

        stack<string> pathRecoder;
        for(int i=0;i<path.size();)
        {
            while(path[i]=='/'&&i<path.size())
            {
                i++;
            }
            string tempStr="";
            while(path[i]!='/'&&i<path.size())
            {
                tempStr=tempStr+path[i++];
            }
            if(tempStr==".."&&tempStr.empty())
                pathRecoder.pop();
            else if(tempStr!=""&&tempStr!="."&&tempStr!="..")
                pathRecoder.push(tempStr);
        }
        string result="";
        if(pathRecoder.empty())
        {
            return"/";
        }
        while(!pathRecoder.empty())
        {

            result="/"+result+pathRecoder.top();
            pathRecoder.pop();
        }
        return result;
    }
 };



Results:




发布了35 篇原创文章 · 获赞 0 · 访问量 4640
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章