码迷,mamicode.com
首页 > 其他好文 > 详细

simplify-path

时间:2016-11-05 20:04:08      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:static   字符串   led   void   printf   on()   turn   out   throws   

https://leetcode.com/problems/simplify-path/

https://leetcode.com/mockinterview/session/result/xjl3d3m/

现在字符串比较,都知道用 equals了,哈哈。不能用==,否则可能有bug。

 

package com.company;


import java.util.*;

class Solution {
    public String simplifyPath(String path) {
        Stack<String> stk= new Stack<>();
        String[] strs = path.split("/");
        for (int i=0; i<strs.length; i++) {
            if (strs[i].equals("") || strs[i].equals(".")) {
                continue;
            }
            else if (strs[i].equals("..")) {
                if (!stk.empty()) {
                    stk.pop();
                }
            }
            else {
                stk.push(strs[i]);
            }
        }

        Stack<String> newStk= new Stack<>();
        String tmp;
        while (!stk.empty()) {
            tmp = stk.pop();
            newStk.push(tmp);
        }

        StringBuilder sb = new StringBuilder();
        while (!newStk.empty()) {
            sb.append("/" + newStk.pop());
        }
        String str = sb.toString();
        if (str.equals("")) {
            str = "/";
        }
        return str;
    }
}

public class Main {

    public static void main(String[] args) throws InterruptedException {

        System.out.println("Hello!");
        Solution solution = new Solution();

        // Your Codec object will be instantiated and called as such:
        String path = "/a/./b/../../c/";
        String ret = solution.simplifyPath(path);
        System.out.printf("ret:%s\n", ret);

        System.out.println();

    }

}

 

simplify-path

标签:static   字符串   led   void   printf   on()   turn   out   throws   

原文地址:http://www.cnblogs.com/charlesblc/p/6033695.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!