zoukankan      html  css  js  c++  java
  • LeetCode: Simplify Path

    改了很多次,这种麻烦的题目就是考你有没有考虑到所有情况

     1 class Solution {
     2 public:
     3     string simplifyPath(string path) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         vector<string> S;
     7         string tmp = "";
     8         for (int i = 0; i < path.size(); i++) {
     9             if (path[i] == '/') {
    10                 if (!tmp.size()) continue;
    11                 else {
    12                     if (tmp == "..") {
    13                         if (S.size()) S.pop_back();
    14                     }
    15                     else if (tmp != ".") S.push_back(tmp);
    16                     tmp = "";
    17                 }
    18             }
    19             else tmp = tmp + path[i];
    20         }
    21         if (tmp.size()) {
    22             if (tmp == ".") ;
    23             else if (tmp == "..") {
    24                 if (S.size()) S.pop_back();
    25             }
    26             else S.push_back(tmp);
    27         }
    28         string ret = "";
    29         for (int i = 0; i < S.size(); i++) {
    30             ret = ret + "/" + S[i];
    31         }
    32         if (!ret.size()) return "/";
    33         return ret;
    34     }
    35 };

     C#

     1 public class Solution {
     2     public string SimplifyPath(string path) {
     3         Stack<string> S = new Stack<string>();
     4         string tmp = "";
     5         for (int i = 0; i < path.Length; i++) {
     6             if (path[i] == '/') {
     7                 if (tmp.Length == 0) continue;
     8                 else {
     9                     if (tmp == "..") {
    10                         if (S.Count > 0) S.Pop();
    11                     }
    12                     else if (tmp != ".") S.Push(tmp);
    13                     tmp = "";
    14                 }
    15             }
    16             else tmp += path[i];
    17         }
    18         if (tmp.Length > 0) {
    19             if (tmp == ".") ;
    20             else if (tmp == "..") {
    21                 if (S.Count > 0) S.Pop();
    22             }
    23             else S.Push(tmp);
    24         }
    25         string ans = "";
    26         while (S.Count > 0) {
    27             ans = S.Peek() + "/" + ans;
    28             S.Pop();
    29         }
    30         if (ans.Length == 0) return "/";
    31         ans = "/" + ans;
    32         return ans.Substring(0, ans.Length - 1);
    33     }
    34 }
    View Code
  • 相关阅读:
    Windows环境下阿里云添加SSH Key及Git配置Key
    Shiro自定义注解扩展@SalmonRequiresPermission
    windows下安装redis
    模型-视图-控制器的C++解释
    CentOS 7 搭建 GitLab
    博客园主题分享——绿色
    2019年的第一篇博客
    Qt——线程与定时器
    Qt——线程类QThread
    QML——添加自定义模块
  • 原文地址:https://www.cnblogs.com/yingzhongwen/p/3033427.html
Copyright © 2011-2022 走看看