[LeetCode] 388. Longest Absolute File Path

Chobby·2026년 1월 30일

LeetCode

목록 보기
980/993

😎풀이

  1. input 요소를 줄바꿈 기호 기준으로(depth에 따라) 분리
  2. 분리된 파일 순회
    2-1. 현재 요소의 depth를 탭 기호 기준으로 판단
    2-2. 실제 파일명에서 탭 기호 분리
    2-3. 파일이라면, 누적된 길이 + 현재 파일명의 길이로 절대 경로 최장길이 갱신
    2-4. 폴더라면, 누적된 길이 + 현재 폴더명의 길이로 depth 갱신
  3. 최장 절대경로의 길이 반환
function lengthLongestPath(input: string): number {
    const files = input.split("\n")
    const depthLen = new Map<number, number>()
    let longestPathLen = 0
    for(const file of files) {
        const depth = (file.match(/[\t]/g) ?? '').length
        const curFileNameLen = file.length - depth
        const totalLen = (depthLen.get(depth - 1) ?? 0) + curFileNameLen
        if(!file.includes('.')) {
            depthLen.set(depth, totalLen + 1)
            continue
        }
        longestPathLen = Math.max(longestPathLen, totalLen)
    }
    return longestPathLen
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글