[LintCode] Simplify Path [字符串操作]
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è)上層的segmentChallenge
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語(yǔ)句返回slash就可以了,"/../"本身要綜合Example的例子,pop出上一層元素。
Multiple slashes,可以用split()函數(shù)去掉所有slash,然后多考慮一個(gè)slash中間為空的case。
關(guān)于switch語(yǔ)句的一個(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 [字符串操作]的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 酒吧企业文化标语文案29句
- 下一篇: 草房子读后感600字左右