【Simplify Path】cpp

题目:

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

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

click to show corner cases.

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

代码:

class Solution {
public:
    string simplifyPath(string path) {
            string result = "";
            path.append("/"); // some input path not end with "/"
            vector<string> ret; // use vector acting as stack
            string tmp_part = "";
            ret.push_back(string(1,path[0]));
            for ( size_t i = 1; i < path.size(); ++i ){
                if ( path[i]==‘/‘ ){
                    if ( tmp_part==".." ){
                        if ( ret.size()>1 )
                        {
                            ret.erase(ret.end()-1);
                            ret.erase(ret.end()-1);
                        }
                    }
                    else
                    {
                        if ( tmp_part!="" && tmp_part!="." )
                        {
                            ret.push_back(tmp_part);
                            ret.push_back("/");
                        }
                    }
                    tmp_part = "";
                }
                else
                {
                    tmp_part += path[i];
                }
            }
            if ( ret.size()>1 && ret[ret.size()-1]=="/" ) ret.erase(ret.end()-1);
            for ( size_t i = 0; i < ret.size(); ++i ) result += ret[i];
            return result;
    }
};

tips:

主要思想是stack堆栈的数据结构。

1. 利用"/"来作为间隔判断符号

2. tmp_part为两个"/"之间的字符串部分(需要注意输入的path可能不以"/"结尾,解决办法是人工在path后面补上一个)

3. 如果tmp_part为“..”,则出栈两个元素(前提是栈中元素数目足够)

如果tmp_part不为“.”, 且不为".",且不为"", 则入栈(注意,还要包括后面的“/”)

其他部分靠题目提供的一些corner cases来debug了。

这里用到的一个技巧是vector来代替stack;这样做的好处是返回结果时不用将stack的元素倒序组合。

时间: 2024-11-20 17:03:38

【Simplify Path】cpp的相关文章

【Word Break】cpp

题目: Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, givens = "leetcode",dict = ["leet", "code"]. Return true becau

【Sudoku Solver】cpp

题目: Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by the character '.'. You may assume that there will be only one unique solution. A sudoku puzzle... ...and its solution numbers marked in red. 代码: cla

【Subsets II】cpp

题目: Given a collection of integers that might contain duplicates, nums, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example,If nums = [1,2,2], a sol

【LRU Cache】cpp

题目: Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.

【Rotate List】cpp

题目: Given a list, rotate the list to the right by k places, where k is non-negative. For example:Given 1->2->3->4->5->NULL and k = 2,return 4->5->1->2->3->NULL. 代码: /** * Definition for singly-linked list. * struct ListNode {

【Text Justification】cpp

题目: Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pa

【Implement strStr() 】cpp

题目: Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. Update (2014-11-02):The signature of the function had been updated to return the index instead of the pointer. If you st

【Valid Palindrome】cpp

题目: Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example,"A man, a plan, a canal: Panama" is a palindrome."race a car" is not a palindrome. Note:Have you consider tha

【Jump Game】cpp

题目: Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index. For example: