C# solution


  • 0
    H
    public string SimplifyPath(string path) {
            string[] parts = path.Split('/');
            List<string> segments = new List<string>();
            
            for(int i = 0; i < parts.Length; i++) {
                if (string.IsNullOrEmpty(parts[i]) || parts[i] == ".") continue;
                if (parts[i] == "..") { if (segments.Count > 0) segments.RemoveAt(segments.Count - 1); }
                else segments.Add(parts[i]);
            }
            
            StringBuilder sb = new StringBuilder();
            foreach(string segment in segments) {
                sb.Append("/" + segment);
            }
            
            if (sb.Length == 0) sb.Append("/");
            
            return sb.ToString();
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.