반응형
SMALL
문제
풀이
using System;
using System.Collections.Generic;
namespace Programmers
{
class Program
{
static void Main()
{
string[] testcase = //테스트 케이스 문자열 배열 생성 후 초기화
{
"12","123","1235","567","88"
};
Solution sol = new Solution(); //솔루션 클래스 생성
List<string> nums = new List<string>(testcase); //테스트 케이스를 담을 문자열넘버 리스트 생성
bool result = sol.solution(nums); // 솔루션 클래스의 솔루션 매서드 사용
Console.WriteLine(result); // 결과 값 출력
}
}
class Solution
{
public bool solution(List<string> nums)
{
bool answer = true; //기본 값 true
for (int i = 1; i < nums.Count; i++) //리스트를 돌며 인덱스 요소를 확인
{
if (nums[i].Contains(nums[0])) //nums 리스트의 0번째 인덱스 요소가 포함된 다른 인덱스를 탐색
{
answer = false; //있다면 부울값 false 후 break;
break;
}
}
return answer; // 없었다면 그대로 true 출력
}
}
}
결과창
이렇게 풀었는데 처음에는 해시를 사용해서 풀려고 했으나 의외로 리스트로도 문제없이 풀리는듯하여 찝찝함(;;) 을 느끼고 선생님께서 푸신 방법을 참고해보았다.
해시를 이용한 풀이
using System;
using System.Collections.Generic;
namespace Programmers
{
class Program
{
static void Main()
{
//
//List<string> phoneBook = new List<string>(new string[]{"119", "97674223", "1195524421"});
List<string> phoneBook = new List<string>(new string[] { "123", "456", "789" });
var result = new Solution().solution(phoneBook);
Console.WriteLine(result);
}
}
class Solution
{
public bool solution(List<string> phone_book)
{
bool answer = true;
Dictionary<string, int> dic = new Dictionary<string, int>();
for (int i = 0; i < phone_book.Count; i++)
{
dic.Add(phone_book[i], 1);
}
for (int i = 0; i < phone_book.Count; i++)
{
var phone_number = "";
var len = phone_book[i].Length;
for (int j = 0; j < len; j++)
{
phone_number += phone_book[i][j];
if (dic.ContainsKey(phone_number) && phone_number != phone_book[i])
answer = false;
}
}
return answer;
}
}
}
해시를 이용하면 리스트의 각 인덱스 요소의 0번째 문자부터 차례로 더해가며 Dictionary의 다른 Key들과 비교하며 공통된 번호를 포함한 Key 가 있는지 확인이 가능했고 이걸 보다 문제의 예시만 보고 너무 섣불리 판단했다는걸 알았다
" 주어진 번호중 무조껀 0번째 인덱스 요소와 겹치는 번호를 찾는게 아니라 모든 인덱스 요소중 공통되는 번호를 가지고 있는 요소가 있는지 확인" 하는 거였다 (ㅠㅜ)
내가 한 방식으로는 0번째 인덱스 요소와 겹치는 번호가 있는지는 찾을수는 있지만 만약 1번째 인덱스와 2번째 인덱스 요소가 겹친다면 해당 사항은 찾아낼수 없는 코드였다.
해시 관련 문제를 좀더 풀어보는편이 좋을듯하다.
반응형
LIST
'Algorithm > BOJ' 카테고리의 다른 글
[BOJ] 2869번 달팽이는 올라가고 싶다. C#사용 풀이 (0) | 2023.01.25 |
---|---|
[BOJ] 9012 괄호 (0) | 2023.01.24 |
[프로그래머스] 다트게임 C#풀이 (0) | 2023.01.23 |
[BOJ] 10822 더하기 C# 사용 풀이 (0) | 2023.01.23 |
[BOJ] 1254 팰린드롬 만들기 c# 사용 풀이 (0) | 2023.01.23 |