[Java] 프로그래머스 배열의 유사도

2023. 2. 1. 13:58알고리즘

728x90

문제 설명

두 배열이 얼마나 유사한지 확인해보려고 합니다. 문자열 배열 s1과 s2가 주어질 때 같은 원소의 개수를 return하도록 solution 함수를 완성해주세요.

제한사항

  • 1 ≤ s1, s2의 길이 ≤ 100
  • 1 ≤ s1, s2의 원소의 길이 ≤ 10
  • s1과 s2의 원소는 알파벳 소문자로만 이루어져 있습니다
  • s1과 s2는 각각 중복된 원소를 갖지 않습니다.

입출력 예

입출력 예 설명

입출력 예 #1

  • "b"와 "c"가 같으므로 2를 return합니다.

입출력 예 #2

  • 같은 원소가 없으므로 0을 return합니다.

코드 설명

import java.util.Scanner;

public class Solution {
	public int solution(String[] s1, String[] s2) {
        int answer = 0;
        
        for (int i = 0; i < s1.length; i++) { // ex) s1 = [a,b,c], s2 = [com,b,d,p,c]
        	for (int j = 0; j < s2.length; j++) {	
        		if (s1[i].equals(s2[j])) { // s1[i]값이 s2[j]랑 같으면 answer 1증가
        			answer++; // s1[0].equals(s2[0~4]), s1[1].equals(s2[0~4]), s1[2].equals(s2[0~4])
        		} // answer = b,c가 같으므로 2
        	}
        }
        
        return answer;
    }
	public static void main(String[] args) {
		Solution T = new Solution();
		Scanner sc = new Scanner(System.in);
		int num = sc.nextInt();
		int num2 = sc.nextInt();
		String[] s1 = new String[num];
		String[] s2 = new String[num2];
		for (int i = 0; i < num; i++) {
			s1[i] = sc.next();
		}
		for (int j = 0; j < num2; j++) {
			s2[j] = sc.next();
		}
		System.out.println(T.solution(s1, s2));
		sc.close();
	}
}
728x90