반응형
문제
문자열 S의 부분 문자열이란, 문자열의 연속된 일부를 의미한다.
예를 들어, "aek", "joo", "ekj"는 "baekjoon"의 부분 문자열이고, "bak", "p", "oone"는 부분 문자열이 아니다.
문자열 S와 P가 주어졌을 때, P가 S의 부분 문자열인지 아닌지 알아보자.
입력
첫째 줄에 문자열 S, 둘째 줄에 문자열 P가 주어진다. 두 문자열은 빈 문자열이 아니며, 길이는 100만을 넘지 않는다. 또, 알파벳 소문자로만 이루어져 있다.
출력
P가 S의 부분 문자열이면 1, 아니면 0을 출력한다.
16916번: 부분 문자열
첫째 줄에 문자열 S, 둘째 줄에 문자열 P가 주어진다. 두 문자열은 빈 문자열이 아니며, 길이는 100만을 넘지 않는다. 또, 알파벳 소문자로만 이루어져 있다.
www.acmicpc.net

풀이 코드
바로 이전 포스팅에 작성한 KMP 알고리즘을 이용해서 해당 문제를 풀어보았다.
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
var s = Console.ReadLine();
var pattern = Console.ReadLine();
Console.WriteLine(KMP(s, pattern) ? "1" : "0");
}
static bool KMP(string s, string pattern)
{
var piList = GetPi(s);
int begin = 0;
int match = 0;
while(begin + match < s.Length)
{
if (match < pattern.Length && s[begin + match] == pattern[match])
{
match++;
if (pattern.Length == match)
{
return true;
}
}
else
{
if (match == 0)
{
begin++;
}
else
{
begin += match - piList[match - 1];
match = piList[match - 1];
}
}
}
return false;
}
static List<int> GetPi(string s)
{
List<int> list = new List<int>();
for (int i = 0; i < s.Length; i++)
{
list.Add(0);
}
int begin = 1;
int match = 0;
while(begin + match < s.Length)
{
if (s[begin + match] == s[match])
{
match++;
list[begin + match - 1] = match;
}
else
{
if (match == 0)
{
begin++;
}
else
{
begin += match - list[match - 1];
match = list[match - 1];
}
}
}
return list;
}
}
함께 보면 좋은 글
KMP 문자열 탐색 알고리즘
KMP 문자열 탐색 알고리즘 글 안에서 단어를 빠르게 찾거나, 문자열을 전처리하여 우리가 원하는 정보를 추출하는 알고리즘은 여러 분야에서 활용이 가능하다. 대표적인 문자열 안에서 단어를
jettstream.tistory.com
'프로그래밍 > Algorithm' 카테고리의 다른 글
[프로그래머스 Programmers] 소인수분해 (0) | 2024.02.22 |
---|---|
[백준 BAEKJOON] 1929번 소수 구하기 (1) | 2024.02.21 |
KMP 문자열 탐색 알고리즘 (0) | 2024.02.19 |
[백준 BAEKJOON] 2557번 Hello World (0) | 2024.02.16 |
C# 힙 트리(Heap tree) 구현 (1) | 2024.02.05 |
댓글