본문 바로가기

코딩테스트/LeetCode

[LeetCode] Find And Replace Pattern

문제링크

 

Find and Replace Pattern - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

words의 단어들 중 pattern으로 주어진 문자열의 패턴과 같은 단어를 찾아라.
ex) "aabbcc", "ggffee" ==> 같은 패턴

접근 방법
"aabbcc"와 "ggffee"의 공통점은 무엇일까?

문자열의 문자를 숫자로 변경하여 표현하면 같을 것 이다.

처음에는 문자열을 배열로 변환하고 Set을 통해 중복을 제거하여 ["g", "f", "e"]를 만들고 
"ggffee".replaceAll("g", index번호) 방식으로 접근하였는데 코드가 복잡하여

indexOf를 통해 접근하였다.


문자열을 입력하면 index번호로 변환하여 반환하는 함수이다.
function replaceWordToIndex (str){
    let result = ""
    for(let i = 0; i < str.length; i++){
        result += str.indexOf(str[i]);
    }
    return result;
}​

 

 

/**
 * @param {string[]} words
 * @param {string} pattern
 * @return {string[]}
 */
var findAndReplacePattern = function(words, pattern) {
    const output = [];
    const target = replaceWordToIndex(pattern);
    
    for(const word of words){
        const wordIndex = replaceWordToIndex(word);
        
        if(wordIndex === target){
            output.push(word);
        }
    }
    
    return output
};

function replaceWordToIndex (str){
    let result = ""
    for(let i = 0; i < str.length; i++){
        result += str.indexOf(str[i]);
    }
    return result;
}

'코딩테스트 > LeetCode' 카테고리의 다른 글

[LeetCode] Kth Smallest Element In A Sorted Matrix  (0) 2022.08.02
[LeetCode] Unique Paths  (0) 2022.08.01
[LeetCode] Valid Anagram  (0) 2022.07.28
[LeetCode] Median Of Two Sorted Arrays  (0) 2022.07.25
[LeetCode] Search A 2d Matrix II  (0) 2022.07.24