Zheaoli / do-something-right

MIT License
37 stars 3 forks source link

2022-01-06 #107

Open Zheaoli opened 2 years ago

Zheaoli commented 2 years ago

2022-01-06

jingkecn commented 2 years ago
/*
 * @lc app=leetcode.cn id=71 lang=csharp
 *
 * [71] 简化路径
 */

// @lc code=start
public class Solution
{
    public string SimplifyPath(string path)
    {
        var stack = new Stack<string>();
        var components = path.Split('/');
        foreach (var component in components)
        {
            if (string.IsNullOrEmpty(component) || component == ".")
            {
                continue;
            }

            if (component == "..")
            {
                stack.TryPop(out _);
                continue;
            }

            stack.Push(component);
        }

        return $"/{string.Join('/', new Stack<string>(stack))}";
    }
}
// @lc code=end

微信id: 我要成為 Dr. 🥬 来自 vscode 插件

sishenhei7 commented 2 years ago
/*
 * @lc app=leetcode.cn id=71 lang=typescript
 *
 * [71] 简化路径
 */

// @lc code=start
function simplifyPath(path: string): string {
  const pathArr = path.split('/')
  const dirArr = []
  for (const p of pathArr) {
    if (p === '.' || p === '') {
      continue
    }

    if (p === '..') {
      dirArr.pop()
      continue
    }

    dirArr.push(p)
  }
  return `/${dirArr.join('/')}`
};
// @lc code=end