日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

[LintCode] Simplify Path [字符串操作]

發(fā)布時(shí)間:2023/12/31 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [LintCode] Simplify Path [字符串操作] 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

Problem

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

Example

"/home/", => "/home" //去掉末尾的slash"/a/./b/../../c/", => "/c" //每個(gè)"/../"對(duì)應(yīng):刪除一個(gè)上層的segment

Challenge

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

Note

關(guān)于challenge的兩點(diǎn):

  • "/../",這里討論的有兩種情況,空集和"/../"本身??占右粋€(gè)if語句返回slash就可以了,"/../"本身要綜合Example的例子,pop出上一層元素。

  • Multiple slashes,可以用split()函數(shù)去掉所有slash,然后多考慮一個(gè)slash中間為空的case。

  • 關(guān)于switch語句的一個(gè)特點(diǎn):

    我們對(duì)case ""和case "."其實(shí)都是不做操作,然而,兩個(gè)case可以都break,但是不能都不做操作。像這樣:

    case "": case ".":

    這樣這兩個(gè)case就都會(huì)等價(jià)于下一個(gè)case:case "..". 就會(huì)出錯(cuò)。

    Solution

    public class Solution {public String simplifyPath(String path) {Stack<String> stack = new Stack<String>();String[] segments = path.split("/");for (String segment: segments) {switch(segment) {case "": break;case ".":case "..": if (!stack.isEmpty()) {stack.pop();}break;default: stack.push(segment);}}StringBuilder sb = new StringBuilder();if (stack.isEmpty()) {//空集的情況return "/";}while (!stack.isEmpty()) {sb.insert(0, "/"+stack.pop());//Don't miss the slash!}return sb.toString();} }

    總結(jié)

    以上是生活随笔為你收集整理的[LintCode] Simplify Path [字符串操作]的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。