본문 바로가기
나의 일기

230526

by sweesweet 2023. 5. 26.

크헝헝허엏헝헝 요새 알고리즘 스터디에서 스택 겁나 털리고있다. 쉽다 해서 풀고있는데 역시나.. 처음 개념만 쉬운건 모든 공부에서 그런것 같다.

오늘도 어떻게든 풀어보겠다고 2시간 반을 매달렸다. 이럼 안되는데...1시간 지나면 솔루션 보고 정리해야하는데..

오기가 생겨서 그냥 풀어재꼈다. 

오늘 푼 문제는

https://leetcode.com/problems/longest-absolute-file-path/

 

Longest Absolute File Path - LeetCode

Can you solve this real interview question? Longest Absolute File Path - Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture: [https://assets.leetcode.com/uploads/2020/08/28

leetcode.com

\t 어떻게 처리하는지 까먹어서 그냥 replaceAll돌려버렸다. 이전에 풀었던 방식이랑 비슷할 것 같긴한데, 오늘 뭐에 씌였는지 문제를 어떻게 풀어야 할지 답이 잡히지 않았다.

/**
 * @param {string} input
 * @return {number}
 */
var lengthLongestPath = function(input) {
    if(input.length===1){
        return 0
    }
    let arr= input.replaceAll('\t','/').split('\n')
    let maxLength=0
    let length=0
    let num=0
    let stack=[]
    for(let i =0;i<arr.length;i++){
        if(stack.length===0){
            stack.push(arr[i])
            length+=arr[i].length
            num++
        }
        else if(arr[i][num-1]==='/'){
            let val=arr[i].slice(num-1)
            if(i===arr.length-1&&!arr[i].includes('.')){
                return maxLength
            }
            stack.push(val)
            length+=val.length
            num++
          
        }else{
            if(stack.at(-1).includes('.')){
                maxLength=Math.max(maxLength,length)
            }
             length-=stack.pop().length
             i--
             num-- 
        }

    }
    return Math.max(maxLength,length)
    
};

스터디에 적어둔 내용이다ㅋ큐

 

문제 풀때 큰 틀

  1. num 즉, / 의 길이로 깊이 측정
  2. num이 증가했는데 해당 위치에 / 있다? stack.pop() 과 그 인덱스 값에 계속 있으면서, 깊이 비교하도록 i—와 num-- 처리
  3. stack에 푸시할 때 /folder 이런식으로 하도록 애초에 그렇게 넣기 (왜냐면 그렇게 안넣었다가 계산하기 까다로웟음..)

문제 풀 때 유의할 점

  1. 폴더/폴더/폴더는 유효한 값이 아니다
  2. num으로 깊이를 측정할 시 같은 깊이의 폴더 혹은 파일들이 나열된 arr를 유의해야 한다

내일 dfs로나 다른 방법으로 다시풀어봐야겠다 거의 답에 구겨넣었다 해도 다를 바가 없어서... 내일도 화이팅

'나의 일기' 카테고리의 다른 글

230801  (0) 2023.08.01
230623  (0) 2023.06.23
230502  (1) 2023.05.02
230308  (0) 2023.03.08
230303  (0) 2023.03.03