void PushDir(MyStackArray <string> stack, StringBuilder sb) { var dir = sb.ToString(); sb.Clear(); switch (dir) { case "": return; case ".": return; case "..": if (!stack.IsEmpty()) { stack.Pop(); } return; default: stack.Push(dir); return; } }
/* A shorter solution by using String.Split * potentially with worse performance * Runtime: 192 ms, faster than 5.02% of C# online submissions for Simplify Path. * Memory Usage: 25 MB, less than 72.15% of C# online submissions for Simplify Path. * using System.Linq; * public string SimplifyPath(string path) * { * if (path.Length == 1) return "/"; * var stack = new MyStackArray<string>(); * var files = path.Split('/').Where(file => file.Length != 0 && file != "."); * foreach (var file in files) * { * if (file == "..") * { * if (!stack.IsEmpty()) * stack.Pop(); * } * else * { * stack.Push(file); * } * } * return "/" + String.Join("/", stack.AsReversedArray()); * } */ public string SimplifyPath(string path) { if (path.Length == 1) { return("/"); } var stack = new MyStackArray <string>(); var sb = new StringBuilder(); var i = 0; while (i != path.Length) { switch (path[i]) { case '.': i += 1; sb.Append('.'); continue; case '/': i += 1; while (i != path.Length && path[i] == '/') { i += 1; } PushDir(stack, sb); continue; default: sb.Append(path[i]); i += 1; continue; } } if (sb.Length != 0) { PushDir(stack, sb); } return("/" + String.Join("/", stack.AsReversedArray())); }