[LeetCode] 524. Longest Word in Dictionary through Deleting

Chobby·3일 전

LeetCode

목록 보기
1042/1046

😎풀이

  1. dictionary 순회
    1-1. result가 더 긴 단어일 경우 비교 불필요
    1-2. result가 동일 길이 단어면서, 사전순으로 더 빠르다면 비교 불필요
    1-3. s의 특정 부분을 빼서 dictionary[i]를 구성할 수 있다면, result 갱신
  2. 가장 긴 단어를 찾았다면 해당 단어 반환 그러지 못했다면 빈 문자열 반환
function findLongestWord(s: string, dictionary: string[]): string {
    const sLen = s.length
    let result = ''
    for(const dict of dictionary) {
        const dictLen = dict.length
        if(result.length > dictLen) continue
        if(result.length === dictLen && result <= dict) continue
        let i = 0
        let j = 0
        while(i < sLen && j < dictLen) {
            if(s[i] === dict[j]) j++
            i++
        }
        if(j !== dictLen) continue
        result = dict
    }
    return result
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글