일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- 이분 탐색
- 시뮬레이션
- 큐
- 유클리드 호제법
- LeetCode 83 c언어
- 정수론
- 문자열
- LeetCode 83번
- LeetCode Remove Duplicates from Sorted List in c
- 브루트포스 알고리즘
- 프로그래머스
- 큰 수 연산
- 임의 정밀도 / 큰 수 연산
- 수학
- 문자열제곱
- 해시를 사용한 집합과 맵
- 별 찍기
- Queue
- 사칙연산
- 정렬
- 자료 구조
- 연결리스트 중복제거
- 스택
- 재귀
- KMP알고리즘
- 연결리스트 정렬
- 조합론
- 실패함수
- 구현
- 다이나믹 프로그래밍
- Today
- Total
hahn
[LeetCode - C] 28. Implement strStr() 본문
Implement strStr() - 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
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Example 3:
Input: haystack = "", needle = ""
Output: 0
Constraints:
- 0 <= haystack.length, needle.length <= 5 * 104
- haystack and needle consist of only lower-case English characters.
Solution 1
처음에는 i, j 이용해 haystack[i]마다
처음부터 끝까지 needle 검사했다.
결과는 잘 나오지만 time limit에 걸려 통과가 안 돼서
실패 함수 이용하여 kmp알고리즘으로 해결했다.
[알고리즘] 실패함수(문자열 검색 - KMP 알고리즘 관련)
4354번: 문자열 제곱 (acmicpc.net) 4354번: 문자열 제곱 알파벳 소문자로 이루어진 두 문자열 a와 b가 주어졌을 때, a*b는 두 문자열을 이어붙이는 것을 뜻한다. 예를 들어, a="abc", b="def"일 때, a*b="abcdef"..
ahnstu.tistory.com
int strStr(char * haystack, char * needle)
{
if (!*needle)
return (0);
if (!*haystack)
return (-1);
int failfunc[strlen(needle)];
int i;
int j;
i = 0;
j = 1;
failfunc[0] = 0;
while (needle[j])
{
while (i > 0 && needle[i] != needle[j])
i = failfunc[i - 1];
if (needle[i] == needle[j])
failfunc[j] = ++i;
else
failfunc[j] = 0;
j++;
}
i = 0;
j = 0;
while (haystack[i])
{
while (j > 0 && haystack[i] != needle[j])
j = failfunc[j - 1];
if (haystack[i] && needle[j] && haystack[i] == needle[j])
j++;
if(!needle[j])
return (i - j + 1);
i++;
}
return (-1);
}
총평
전에 실패함수를 한 번 정리 했음에도 어떻게 하는건지
생각나지 않아서 한참 보고 나서 실패 함수 이용하여
혼자서 해결하려했는데 아이디어가 잘 떠오르지 않아
kmp알고리즘 참고해서 풀었다.
'코딩테스트 연습 > LeetCode(C - Easy)' 카테고리의 다른 글
[LeetCode - C] 53. Maximum Subarray (0) | 2022.04.12 |
---|---|
[LeetCode - C] 35. Search Insert Position (0) | 2022.04.06 |
[LeetCode - C] 27. Remove Element (0) | 2022.03.25 |
[LeetCode - C] 26. Remove Duplicates from Sorted Array (0) | 2022.03.25 |
[LeetCode - C] 21. Merge Two Sorted Lists (0) | 2022.03.24 |