Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- [파이썬 실습] 기초 문제
- 자바스크립트 날씨
- JavaScript
- leetcode
- 부트캠프
- 자바스크립트 reduce()
- 프론트개발공부
- 코드스테이츠
- 자바스크립트 sort()
- reactnativecli
- 엘리스
- 삼항연산자
- 엘리스 AI 트랙 5기
- 엘리스 ai 트랙
- 프론트개발
- 프로그래머스
- 개발공부
- 간단한 날씨 웹 만들기
- HTML
- 날씨 웹 만들기
- [파이썬 실습] 심화 문제
- [AI 5기] 연습 문제집
- 개발일기
- [파이썬 실습] 중급 문제
- 자바스크립트
- 자바스크립트 split()
- 자바스크립트 날씨 웹 만들기
- 코딩부트캠프
- RN 프로젝트
- 리트코드
Archives
- Today
- Total
개발조각
[리트코드] 28. Find the Index of the First Occurrence in a String 본문
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
반응형
'알고리즘🅰 > 리트코드' 카테고리의 다른 글
[리트코드] 35. Search Insert Position (0) | 2022.09.30 |
---|---|
[리트코드] 29. Divide Two Integers (0) | 2022.09.28 |
[리트코드] 27. Remove Element (0) | 2022.09.26 |
[리트코드] 26. Remove Duplicates from Sorted Array (0) | 2022.09.25 |
[리트코드] 22. Generate Parentheses (0) | 2022.09.25 |
Comments