71. Simplify Path(java)

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".
这道题主要考察对各种case的考虑,具体实现上就是字符串的处理,另外就是最后的reverse有点麻烦。
public String simplifyPath(String path) {
        //special case
        if (path.length() == 0) return "";
        if (path.length() == 1) return "/";
        //general case
        Stack<String> stack = new Stack<>();
        String[] strings = path.split("/");
        for (int i = 0; i < strings.length; i++) {
            String str = strings[i];
            if (str.equals(".") || str.equals("")) {
                continue;
            } else if (str.equals("..")) {
                if (!stack.isEmpty()) {
                    stack.pop();
                }
            } else {
                stack.push(str);
            }
        }
        if (stack.isEmpty()) return "/";
        String res = "";
        while (!stack.isEmpty()) {
            res = "/" + stack.pop() + res;
        }
        return res;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
sympy.simplify函数是SymPy中的一个函数,用于简化数学表达式。它可以将复杂的表达式转化为更简单的形式,例如,将分数约分、将多项式因式分解等。 使用方法: 1. 导入sympy库 import sympy 2. 定义需要简化的表达式 expr = sympy.simplify(expression) 其中expression为需要简化的表达式,可以是字符串或SymPy表达式。 3. 示例 以下是一些使用sympy.simplify函数的示例: 1. 约分分数 expr = sympy.simplify("6/12") print(expr) 输出结果为: 1/2 2. 合并同类项 expr = sympy.simplify("x + 2x + 3x") print(expr) 输出结果为: 6x 3. 求导后简化 x = sympy.Symbol('x') expr = sympy.diff(sympy.sin(x)**2 + sympy.cos(x)**2, x) print(expr) expr = sympy.simplify(expr) print(expr) 输出结果为: 0 0 4. 将三角函数化简 x = sympy.Symbol('x') expr = sympy.sin(x)/sympy.cos(x) print(expr) expr = sympy.simplify(expr) print(expr) 输出结果为: tan(x) 5. 将多项式因式分解 x = sympy.Symbol('x') expr = x**2 + 2*x + 1 print(expr) expr = sympy.simplify(expr) print(expr) 输出结果为: (x + 1)**2 6. 将指数函数化简 x = sympy.Symbol('x') expr = sympy.exp(x)*sympy.exp(-x) print(expr) expr = sympy.simplify(expr) print(expr) 输出结果为: 1 7. 将对数函数化简 x = sympy.Symbol('x') expr = sympy.log(sympy.exp(x)) print(expr) expr = sympy.simplify(expr) print(expr) 输出结果为: x 总结: sympy.simplify函数可以用于简化各种类型的数学表达式,包括分数、多项式、三角函数、指数函数和对数函数等。在使用时,需要注意表达式的类型和需要简化的部分,以获得正确的结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值