zoukankan      html  css  js  c++  java
  • Leetcode Simplify Path

    题目

    总结

    1. 做这种题时需要考虑 corner case, 比如连续几个 slash

    2. 状态函数带参数 (int &pos), 主函数带 while 循环 while(pos < len), 我意识到对于 char* 或 string 操作时, 参数带上 lenth 也是蛮好的

    3. 这次很快就 A 了, 甚至忘记以前为什么会在这里栽跟头

    代码

    string getFolderName(const string &path, int &i, const int &len)  {
    	string res;
    	while(i < len && path[i] != '/')  {
    		res.push_back(path[i]);
    		i ++;
    	}
    	return res;
    }
    
    class Solution {
    public:
        string simplifyPath(string path) {
      		deque<string> record;
    
      		int i = 0;
      		int len = path.size();
    
      		while(i < len)  {
      			if(path[i] == '/')  {
      				i ++;
      			}  else  {
      				string folderName = getFolderName(path, i, len);
      				if(folderName == ".")  {
      					// do nothing
      				}  else if(folderName.size() == 2 && folderName == "..")  {
      					if(!record.empty())  record.pop_back();
      				}  else  {
      					record.push_back(folderName);
      				}
      			}
      		}
    
      		string simplifiedPath = "";
    		while(!record.empty())  {
    			simplifiedPath.push_back('/');
    			simplifiedPath.append(record.front());
    			record.pop_front();
    		}
    		if(simplifiedPath.size() == 0)  {
    			simplifiedPath = "/";
    		}     
    		return simplifiedPath;
        }
    };
    

      

  • 相关阅读:
    Linux内核使用的GNUC扩展
    linux常用命令--开发调试篇
    代码示例_poll的多路复用
    硬件_红外传感器
    硬件_霍尔感应器
    全志_功能引脚配置_sys_config.fex
    知识_嵌入式常用词汇
    代码示例_Input 按键驱动
    Vmware_安装_tools
    Ubunt_配置_start
  • 原文地址:https://www.cnblogs.com/zhouzhuo/p/3682347.html
Copyright © 2011-2022 走看看