[LintCode] Simplify Path [字符串操作]
Problem
Given an absolute path for a file (Unix-style), simplify it.
Example
"/home/", => "/home" //去掉末尾的slash"/a/./b/../../c/", => "/c" //每個"/../"對應:刪除一個上層的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
關于challenge的兩點:
"/../",這里討論的有兩種情況,空集和"/../"本身。空集加一個if語句返回slash就可以了,"/../"本身要綜合Example的例子,pop出上一層元素。
Multiple slashes,可以用split()函數去掉所有slash,然后多考慮一個slash中間為空的case。
關于switch語句的一個特點:
我們對case ""和case "."其實都是不做操作,然而,兩個case可以都break,但是不能都不做操作。像這樣:
case "": case ".":這樣這兩個case就都會等價于下一個case:case "..". 就會出錯。
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();} }總結
以上是生活随笔為你收集整理的[LintCode] Simplify Path [字符串操作]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 酒吧企业文化标语文案29句
- 下一篇: hdu 5256 序列变换 (LIS变形