9. [Java] 배열의 유사도(배열, Set) - set.contains(str)

https://school.programmers.co.kr/learn/courses/30/lessons/120903

Set 을 활용한 코드

import java.util.*;

class Solution {
    public int solution(String[] s1, String[] s2) {
        Set<String> set = new HashSet<>(Arrays.asList(s1));
        int cnt = 0;
        for (String str : s2) {
            if (set.contains(str)) cnt++;
        }
        return cnt; 
    }
}


✅ Set<String> set = new HashSet<>(Arrays.asList(s1));


이중 for문(반복문)을 사용한 코드

class Solution {
    public int solution(String[] s1, String[] s2) {
        int cnt = 0;
        for (int i = 0; i < s1.length; i++) {
            for (int j = 0; j < s2.length; j++) {
                if (s1[i].equals(s2[j])) {
                    cnt++;
                    break;
                }
            }
        }
        return cnt;
    }
}



Revision #3
Created 20 May 2025 00:12:32 by Dain
Updated 23 May 2025 04:25:28 by Dain