LeetCode算法系列:71. Simplify Path

版权声明:由于一些问题,理论类博客放到了blogger上,希望各位看官莅临指教https://efanbh.blogspot.com/;本文为博主原创文章,转载请注明本文来源 https://blog.csdn.net/wyf826459/article/details/82767426

目录

 

题目描述

算法实现

关于字符串分割

题目描述

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

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

In a UNIX-style file system, a period ('.') refers to the current directory, so it can be ignored in a simplified path. Additionally, a double period ("..") moves up a directory, so it cancels out whatever the last directory was. For more information, look here: https://en.wikipedia.org/wiki/Path_(computing)#Unix_style

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

算法实现

  • 首先将path按照'/'为间隔分开成字符串组
  • 对字符串组的每一个元素进行判断,建立一个新的字符串数组
    • 如果该元素为空("/")或者为点(".")则直接跳过,
    • 如果该元素为双点("..")则需判断新字符串数组是否为空,若非空,则将最后一个元素删除
    • 如果为其他元素,则直接加入新字符串组
  • 最后将新字符串组的每一个元素前面加'/'并连成一个字符串返回,即结果
class Solution {
public:
    //分割字符串的函数,将字符串沿字符token分开成字符串集合
    vector<string> split(string s,char token){
        istringstream iss(s);
        string word;
        vector<string> vs;
        while(getline(iss,word,token)){
            vs.push_back(word);
        }
        return vs;
    }
    string simplifyPath(string path) {
        if(path.empty() || path.length() == 0)return path;
        vector<string> words = split(path,'/');
        vector<string> suanz;
        string res;
        for(auto word:words){            
            if(word == "." || word.length() == 0)continue;
            else if(word == "..")
                //下面这个大括号必须要加,不然下面的else会被误解为下面的if语句的
            {
                if(!suanz.empty())suanz.pop_back();
            }                
            else{
                suanz.push_back(word);
            }
                
        }
        if(suanz.size() == 0)return "/";
        else
            for(auto word:suanz)
            {
                res += "/";
                res += word;
            } 
        return res;
    }
};

关于字符串分割

    vector<string> split(string s,char token){
        istringstream iss(s);
        string word;
        vector<string> vs;
        while(getline(iss,word,token)){
            vs.push_back(word);
        }
        return vs;
    }

这个函数是参考网络上其他博主的,可以将字符串沿着字符token的位置分割开。在这个函数中,istringstream 将字符串s转换成了一个数据流,而getline(iss,word,token)则是得到字符串的一部分,C++reference的参考如下:

(1)	
istream& getline (istream&  is, string& str, char delim);
istream& getline (istream&& is, string& str, char delim);
(2)	
istream& getline (istream&  is, string& str);
istream& getline (istream&& is, string& str);
  • Extracts characters from is and stores them into str until the delimitation character delim is found (or the newline character, '\n', for (2)).
  • The extraction also stops if the end of file is reached in is or if some other error occurs during the input operation.
  • If the delimiter is found, it is extracted and discarded (i.e. it is not stored and the next input operation will begin after it).
  • Note that any content in str before the call is replaced by the newly extracted sequence.
  • Each extracted character is appended to the string as if its member push_back was called.

其中参数

//Parameters
is
istream object from which characters are extracted.
str
string object where the extracted line is stored.
The contents in the string before the call (if any) are discarded and replaced by the extracted line.

写了两个例子如下:

// extract to string
#include <iostream>
#include <string>

int main ()
{
  std::string name;

  std::cout << "Please, enter your full name: ";
  std::getline (std::cin,name,'/');
  std::cout << "Hello, " << name << "!\n";

  return 0;
}

//result
Please, enter your full name: Wang/yi/Fan
Hello, Wang!
// extract to string
#include <iostream>
#include <string>

int main ()
{
  std::string name;

  std::cout << "Please, enter your full name: ";
  std::getline (std::cin,name);
  std::cout << "Hello, " << name << "!\n";

  return 0;
}

//result
Please, enter your full name: Efan
Hello, Efan!

猜你喜欢

转载自blog.csdn.net/wyf826459/article/details/82767426