알고리즘🅰/리트코드
[리트코드] 28. Find the Index of the First Occurrence in a String
개발조각
2022. 9. 27. 12:38
728x90
반응형
문제
https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/
Find the Index of the First Occurrence in a String - 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 strStr = function(haystack, needle) {
const regex = new RegExp(needle);
let found = haystack.match(regex)
return found ? found.index: -1
};
const regex = new RegExp(needle);
먼저 정규식을 써주어야 합니다.
마음 같아서 아래와 같이 넣어주고 끝내버리고 싶지만
haystack.match(/[sad]/);
이리저리 써봐도 안되는 걸 보니 그냥 위에 같이 써야 되는 것 같습니다.
let found = haystack.match(regex);
위에서 만든 정규식 값을 이용해서 match에 담아 줍니다.
// 1번 예제
Input: haystack = "sadbutsad", needle = "sad"
const regex = new RegExp(needle);
let found = haystack.match(regex);
console.log(found) // [ 'sad', index: 0, input: 'sadbutsad', groups: undefined ]
이와 같이 해당 문자열이 있을 경우 found에는 주석과 같은 값이 나옵니다.
이 값을 자세히 보시면 매치되는 문자열의 처음 위치가 몇 번인지 나옵니다.
index: 0 이렇게요.
이 값은 아래와 같이 쓰면 사용하실 수 있습니다.
console.log(found.index) // 0
// 2번 예제
Input: haystack = "leetcode", needle = "leeto"
const regex = new RegExp(needle);
let found = haystack.match(regex);
console.log(found) // null
이와 같이 해당 문자열이 없으면 null이 나옵니다.
return found ? found.index: -1
마지막으로 해당 문자열이 있을 경우는 문자열 처음 위치를 나타내고
아닐 경우에는 -1을 해주면 됩니다.
728x90
반응형