美文网首页LeetCode
71. Simplify Path

71. Simplify Path

作者: 小万叔叔 | 来源:发表于2017-02-03 14:40 被阅读9次
/*
Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
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".
*/

/*
Thinking:
1. 遇到 .. 丢弃前面一项,. 直接跳过, ...则要保留。
2. 遇到双 // 则要变为到 / 。
3. 尾部的 / 要丢弃。

考虑字符串分割的特性,// 会被 / 分割,则空的子串会被丢弃
所以先把字符串分割为数组,然后过滤空内容,遇到 .. 则把前面的丢弃。
*/

import Foundation

class Solution {
    func simplifyPath(_ path: String) -> String {
        guard path.lengthOfBytes(using: .ascii) > 0 else {
            return ""
        }

        guard path != "/" else {
            return "/"
        }

        let pathArray = path.components(separatedBy: "/")
        let unEmptyArray = pathArray.filter() {
            !($0 as String).isEmpty
        }

        var retArray: [String] = []
        for value in unEmptyArray {
            if value == ".." {
                //如果包含 . 则情况之前的
                if !retArray.isEmpty {
                    retArray.removeLast()
                }
            } else if value != "." {
                retArray.append(value)
            }
        }

        var retStr = "/"
        for value in retArray {
            retStr.append(value)
            if retArray.last != value {
                //非最后一个的情况下, 合并 "/"
                retStr.append("/")
            }
        }

        print(retStr)
        return retStr
    }
}

let solution = Solution()
solution.simplifyPath("/.")

相关文章

网友评论

    本文标题:71. Simplify Path

    本文链接:https://www.haomeiwen.com/subject/gssdittx.html