🤖המדריך להייטיקיסט המתחיל
בינוניLeetCode #71

Simplify Path

עשויה להישאל ב:MetaAmazon

תיאור השאלה

Given an absolute Unix-style file path path, return its simplified canonical form.

  • . refers to the current directory and .. to the parent directory.
  • Multiple consecutive slashes are treated as a single slash.
  • The canonical path starts with a single /, separates directories with a single /, and does not end with a /.

איך פותרים?

מפצלים את הנתיב לפי '/' ומשתמשים במחסנית: חלק ריק או '.' מדלגים, '..' מוציא תיקייה מהמחסנית, וכל שם אחר נדחף. בסוף מחברים את המחסנית עם '/'. סיבוכיות: O(n).

פתרון קוד

JavaScript
Python
function simplifyPath(path) {
  const stack = [];
  for (const part of path.split("/")) {
    if (part === "" || part === ".") continue;
    if (part === "..") {
      stack.pop();
    } else {
      stack.push(part);
    }
  }
  return "/" + stack.join("/");
}
Book Cover

לעבור את ראיון העבודה הבא שלך בהצלחה

קורס דיגיטלי מקיף עם +25 שיעורים מעשיים, כשעתיים של וידאו, וליווי של מראיין בכיר.

התחל עכשיו ב-149 ₪ בלבד! 🚀