개발에 AtoZ까지

[JAVA][Array] Jewels And Stones 본문

코딩테스트 준비/기타문제

[JAVA][Array] Jewels And Stones

AtoZ 개발자 2021. 1. 27. 14:12
반응형

1. 문제

You're given strings J representing the types of stones that are jewels, and S representing the stones you have.
Each character in S is a type of stone you have.
You want to know how many of the stones you have are also jewels.
The letters in J are guaranteed distinct, and all characters in J and S are letters.
Letters are case sensitive, so "a" is considered a different type of stone from "A".

Input: J = "aA", S = "aAAbbbb”
Output: 3

2. 문제 해설

J로 주어진 문자들이 S 문자열에 얼마나 포함되어 있는지 개수를 구하라(대소문자 구분됨)

 

3. 코드 포맷

public class JewelsAndStones {
	public static void main(String args[]) {
		String J = "aA", S = "aAAbbbb";
		System.out.println(solve(J, S));
	}
}

 

4. 접근 방법

J의 문자를 1개씩 잘라서 중복을 방지하는 구조체에 넣어주고 S의 길이만큼 J의 문자가 있는지 확인 작업을 반복한다.

5. 코드

public class JewelsAndStones {
	public static void main(String args[]) {
		String J = "aA", S = "aAAbbbb";
		System.out.println(solve(J, S));
	}

	private static int solve(String j, String s) {
		//중복을 방지
		Set<String> set = new HashSet<String>();
		int count=0;
		for(String str: j.split("")) {
			set.add(str);
		}
		//S에 담겨져 있는지 확인작업
		for(String str:s.split("")) {
			if(set.contains(str)) count++;
		}
		return count;
	}
}

 

반응형

'코딩테스트 준비 > 기타문제' 카테고리의 다른 글

[JAVA][Array] PlusOne  (0) 2021.02.01
[JAVA][Array] KClosestPointstoOrigin  (0) 2021.02.01
[JAVA][Array] LicenseKey Formatting  (0) 2021.01.27
[JAVA][Array] MeetingRoom2  (0) 2021.01.26
[JAVA][Array] MergeInterval  (0) 2021.01.26
[JAVA][Array] Daily Temperature  (0) 2021.01.26
[JAVA][Array] TwoSum  (0) 2021.01.26
Comments