백준
[백준] C# 1120번 : 문자열
l__j__h
2024. 5. 1. 23:08
문제
첨에 몇 번 틀렸다
왜냐면 내가 너무 어렵게 생각했다
문자열 X의 각 글자마다 문자열 Y에서 동일한 idx를 찾고,
문자열 X의 그 글자부터 + 문자열 Y의 해당 idx부터 difference를 비교하며 최솟값을 찾으려고 했는데
이렇게까지 꼬아서 할 필요가 없었다.
예를 들어
문자열 X가 abc 이고, 문자열 Y가 xabce 라고 하면,
abc__ 일 때 diff 값
_abc_ 일 때 diff 값
__abc 일 때 diff 값
을 구하여 최소 diff값을 구하기만 하면 되는 문제였다.
너무 구체적이고 지엽적으로 푸는 것 같을 때는
간단한, 단순한 비교로도 가능하다는 것을 상기해야 겠다.
작성한 코드
using System;
namespace Practice
{
class Program
{
static int Main(string[] args)
{
string input = Console.ReadLine();
string s1 = input.Split(" ")[0];
string s2 = input.Split(" ")[1];
int result = GetDifference(s1, s2, 0);
for (int i = 1; i <= s2.Length - s1.Length; i++)
{
int diff = GetDifference(s1, s2, i);
if (diff < result)
{
result = diff;
}
}
Console.WriteLine(result);
return 0;
}
static int GetDifference(string s1, string s2, int startIndex)
{
int count = 0;
for (int i = 0; i < s1.Length; i++)
{
if (s1[i] != s2[startIndex + i])
count++;
}
return count;
}
}
}
728x90