개발조각

[리트코드] 10. Regular Expression Matching 본문

알고리즘🅰/리트코드

[리트코드] 10. Regular Expression Matching

개발조각 2022. 9. 13. 15:58
728x90
반응형

안녕하세요. 개발조각입니다.😊

이번 문제는 이렇게 풀라는 건 아닌데 이걸 하나하나 구현하기에 좀 싫어서

내장 함수를 써서 구해보았습니다.

그래서 그런지 runtime이 정말 안 좋아요..


https://leetcode.com/problems/regular-expression-matching/submissions/

 

Regular Expression Matching - 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

 

해결방안

var isMatch = function(s, p) {
    const regex = new RegExp(p);
    const regexStr = regex.exec(s);
    
    if(!regexStr) return false;
    return s === regexStr[0] ? true : false;
};

이번 문제를 풀 때 정규식과 같이 사용하는 내장 함수를 사용해서 구해보았습니다.

 

모질라 정규표현식

이 중에서 뭘 쓸지 고민하다가 exec()를 사용해 보았습니다.

 

아래 링크로 들어가시면 exec()에 대해 나와있습니다.

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec

 

RegExp.prototype.exec() - JavaScript | MDN

exec() 메서드는 주어진 문자열에서 일치 탐색을 수행한 결과를 배열 혹은 null로 반환합니다.

developer.mozilla.org

 

const regexStr = regex.exec(s);

 

문자열 s에서 일치한 부분이 있으면 아래와 같이 나오고

[ 'ab', index: 0, input: 'ab', groups: undefined ]

문자열 s에서 일치한 부분이 없으면 아래와 같이 나옵니다.

null

 

이 경우 일치한 부분이 없을 경우를 위해 쓴 코드이고

if(!regexStr) return false;

 

일치하 부분이 있을 경우 [0]가 문자열 s와 같으면 true, 아닐 경우 false로 리턴해주었습니다.

return s === regexStr[0] ? true : false;

 

효율이 안 좋은 건 알지만 빠르게 넘어가는 걸로


정규식 쓰는 걸 까먹어서 구글링 하다가 발견한 건데 편해서 좋더라고요.

정규식 쓸 때 사용하시면 좋을 것 같아요.

https://rubular.com/

 

Rubular

Ruby-based regular expression editor/tester

rubular.com

 

728x90
반응형
Comments