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 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".
=> jewels์ธ ์คํค ํํ๋ฅผ ๋ํ๋ด๋ ์คํธ๋ง J์ ์คํค์ ๋ํ๋ด๋ ์คํธ๋ง S๊ฐ ์ฃผ์ด์ง๋ค. S์ ๊ฐ๊ฐ ์ฒ ์๋ ๋น์ ์ด ๊ฐ์ง ์คํค์ด๋ค. ๋น์ ์ ๋น์ ์ด ๊ฐ์ง ์คํค ์ค jewel์ด ์ผ๋ง๋ ์๋์ง ์๊ณ ์ถ๋ค.
J์ ๋ฌธ์์ด๋ค์ ๊ตฌ๋ณ๋๊ณ , J์ S ์์ ๋ชจ๋ ์ฒ ์๋ค์ ๊ธ์์ด๋ค. ๊ธ์๋ค์ ๋์๋ฌธ์๊ฐ ๊ตฌ๋ถ๋๋ค.
S์ J๋ ์ต๋ 50 ๊ธธ์ด๋ก ๊ตฌ์ฑ๋์ด ์๋ค.
J ์์ character๋ค์ distinctํ๋ค.(๋ถ๋ช
ํ๋ค.๊ตฌ๋ณ๋๋ค.๋๋ ทํ๋ค.)
Solution(๋ด ์๊ฐ)
์๋ฐ์์ ๋ฌธ์์ด์ ๋น๊ตํ๋ ๋ฐฉ๋ฒ
1. equals๋ฅผ ์ด์ฉ : ๋ค๋ฅธ ํ๋ก๊ทธ๋๋ฐ ์ธ์ด์๋ ๋ค๋ฅด๊ฒ ์๋ฐ์์ ==๋ฅผ ์ฌ์ฉํ๋ฉด ๊ฐ์ฒด(Object)๊ฐ ๋์ผํ์ง๋ฅผ ์ฒดํฌํ๊ธฐ ๋๋ฌธ์ object๊ฐ ๊ฐ๋ ๋ฌธ์์ด์ด ๋์ผํ๋ค๋ ๊ฒ์ ๋ณด์ฅํ์ง ์๊ธฐ ๋๋ฌธ์ด๋ค.
2. compare ๋ฉ์๋ ์ด์ฉ
Solution(์ ๋ต)
์ฌ์ฉํ ์๋ฃ๊ตฌ์กฐ : HashSet
์๊ณ ๋ฆฌ์ฆ
1. ๋์๋ฌธ์๋ฅผ ๊ตฌ๋ถ ํ๋ ๋ณด์ ๋ฌธ์๋ฅผ ๊ฐ๊ณ ์์ด์ผ ํ๋ค. - aA : 2๊ฐ
2. ์คํค์ aA๊ฐ ๊ฐ๋ณ์ ์ผ๋ก ๋ช ๊ฐ ์๋์ง ํ์ธํ๋ค.
์ด ๋ฌธ์ ์ ํต์ฌ์ java์ HashSet์ ์ด์ฉํ๋ ๊ฒ์ด๋ค.(์์ ์๊ด์๊ณ , ์ค๋ณต์ ํ์ฉํ์ง ์๋๋ค.)
์๊ณ ๋ฆฌ์ฆ์ java์ธ์ด๋ก ๊ตฌํ
Copy class JewelStones {
public static void main ( String [] args) {
String J = "a,A" , S = "a,A,A,b,b,b,b" ;
System . out . println ( "The number of jewels : " + solve(J , S) );
//int result = solve(s1,s2);๊ตณ์ด ๋ณ์ ์๋ง๋ค์ด๋ ๋ ์ ๋๋ก ๊ฐ๋จ.
}
public static int solve ( String jew , String stone) {
int cnt = 0 ;
Set < Character > set = new HashSet <>();
//1.HashSet์ jewel ๋ฌธ์์ด์ ๋ด๋๋ค.
for ( char jewelChar : jew . toCharArray ()) {
set . add (jewelChar); //a,A๊ฐ HashSet์ ๋ด๊ธด๋ค.
System . out . println ( "char in HashSet :" + jewelChar);
}
//2. stone์ jewel์ด ์ผ๋ง๋ ๋ค์ด์๋์ง ์ฒดํฌํ๋ค!
for ( char stoneChar : stone . toCharArray ()) {
System . out . println ( "stoneChar :" + stoneChar);
if ( set . contains (stoneChar) {
cnt ++ ;
}
}
return cnt;
}
} ๋ฐฐ์ด ๋ด์ฉ ์ ๋ฆฌ
String ํ์
์ ๋ณ์๋ฅผ ์ ์ธ, ๋ฐ์ดํฐ ์ ์ฅํ ๋
2. String์ ์ฒ ์ ํ๋ํ๋ ๋ฅผ ๊ตฌ๋ถํด์ ๋น๊ตํด์ผ ํ ๋ character ํ์
์ set์ด ํ์ํ๋ค.
3. Java์ HashSet
HashSet : ์ปฌ๋ ์
ํ๋ ์์ > Set์ธํฐํ์ด์ค > HashSet
HashSet์ Set ์ธํฐํ์ด์ค๋ฅผ ๊ตฌํํ ๊ฐ์ฅ ๋ํ์ ์ธ ์ปฌ๋ ์
์ด๋ฉฐ, ์์๋ฅผ ์๊ดํ์ง ์๊ณ ์ค๋ณต๋ ์์๋ฅผ ์ ์ฅํ์ง ์๋๋ค. ์์X, ์ค๋ณตX
์์ฑ์ ๋๋ ๋ฉ์๋
HashSet ๊ฐ์ฒด๋ฅผ ์์ฑํ๋ค.
์๋ก์ด ๊ฐ์ฒด๋ฅผ ์ ์ฅํ๋ค.(์ฑ๊ณตํ๋ฉด true, ์คํจํ๋ฉด false)
boolean contains(Object o)
์ง์ ๋ ๊ฐ์ฒด๋ฅผ ํฌํจํ๊ณ ์๋์ง ์๋ ค์ค๋ค.
HashSet์ด ๋น์ด์๋์ง ์๋ ค์ค๋ค.
์ ์ฅ๋ ๊ฐ์ฒด์ ๊ฐ์๋ฅผ ๋ฐํํ๋ค.