https://www.acmicpc.net/problem/1919
1919๋ฒ: ์ ๋๊ทธ๋จ ๋ง๋ค๊ธฐ
๋ ์์ด ๋จ์ด๊ฐ ์ฒ ์์ ์์๋ฅผ ๋ค๋ฐ๊พธ์ด ๊ฐ์์ง ์ ์์ ๋, ๊ทธ๋ฌํ ๋ ๋จ์ด๋ฅผ ์๋ก ์ ๋๊ทธ๋จ ๊ด๊ณ์ ์๋ค๊ณ ํ๋ค. ์๋ฅผ ๋ค๋ฉด occurs ๋ผ๋ ์์ด ๋จ์ด์ succor ๋ ์๋ก ์ ๋๊ทธ๋จ ๊ด๊ณ์ ์๋๋ฐ, occurs
www.acmicpc.net
import java.io.*;
import java.util.List;
class Main{
public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int result = 0;
char[] input = br.readLine().toCharArray();
char[] target = br.readLine().toCharArray();
for (int i=0; i<input.length; i++) {
int idx = List.of(target).indexOf(input[i]);
if (idx != -1) {
target[idx] = '0';
}else{
result += 2;
}
}
System.out.println(result);
}
}
์ค๋ต๋ ธํธ(ํธ๋ ๋์ ์ฌ๊ณ ๊ณผ์ ๋ฐ ๊ฐ์ ์ )
ํ ์คํธ์ผ์ด์ค์์ ๊ฑธ๋ ธ๋ค. idx์์น๋ฅผ ์์๋ด์ ๊ฑฐ๊ธฐ์ ์ํ๋ฒณ์ด ์๋ ๊ฐ์ ๋ฃ๊ณ , indexOf๊ฐ -1๋ฅผ ๋ฐํํ๋ฉด input๋ target๋ ๊ฐ์ด ๋ค๋ฅด๋ค๋ ์๊ธฐ๋๊น ๊ทธ๋ ๋ง๋ค 2๋ฅผ ๋ํ๋ ๋ก์ง์ผ๋ก ์งฐ๋ค. ๋๋ฒ๊น ์ ํด๋ณด๋ indexOf๊ฐ ์ ๋๋ก ๋์ํ๊ณ ์์ง์์๋ค.
indexOf๋ List์ ๋ฉ์๋์ธ๋ฐ ๊ฐ์ index๋ฅผ ๋ฐํํ๋ค.
์ ๋ต์ฝ๋
import java.io.*;
class Main{
public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[] countA = alphabetCount(br.readLine());
int[] countB = alphabetCount(br.readLine());
int ans = 0;
for (int i = 0; i < 26; i++)
ans += Math.abs(countA[i] - countB[i]);
System.out.println(ans);
}
public static int[] alphabetCount(String str) {
int[] count = new int[26];
for (int i = 0; i < str.length(); i++)
count[str.charAt(i) - 'a']++;
return count;
}
}
์ํ๋ฒณ ๋ฐฐ์ด์ ๋ง๋ค์ด์ ์ผ์ข ์ ๊ณ์์ ๋ ฌ ๊ฐ์ด ๋ง๋ค์ด๋ฒ๋ ธ๋ค.
Math.abs๋ก ์ด๋ค๊ฒ ๋ ํฐ์ง ์๊ดํ์ง์๊ณ ์ฐจ์ด ๋๋ ๋งํผ์ ๊ฐ์๋ฅผ ๋ํ๋ค.
์ด๋ฒ ๋ฌธ์ ์์๋ Math.abs์ ์ํ๋ฒณ ๋ฐฐ์ด(a to z 26๊ฐ๋ค)์ ์ฌ์ฉํ๋ ๋ฒ, ๊ทธ๋ฆฌ๊ณ ํจ์๋ก ๋ผ์ด๋ด๋ ๋ฐ์์ ์ตํ์ผํ๋ค.
"๋๊ธ, ๊ณต๊ฐ ๋ฒํผ ํ ๋ฒ์ฉ ๋๋ฅด๊ณ ๊ฐ์ฃผ์๋ฉด ํฐ ํ์ด ๋ฉ๋๋ค"
'OJ๐ผ > ์ค๋ต๋ ธํธ๐' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[BOJ][JAVA] 1236: ์ฑ์งํค๊ธฐ (0) | 2023.10.16 |
---|---|
[BOJ][JAVA] 10158: ๊ฐ๋ฏธ (0) | 2023.10.08 |
[BOJ][JAVA] 13223: ์๊ธํญํ (0) | 2023.10.05 |
[BOJ][JAVA] 1543: ๋ฌธ์ ๊ฒ์ (0) | 2023.10.03 |
[BOJ][JAVA]2744: ๋์๋ฌธ์ ๋ฐ๊พธ๊ธฐ (0) | 2023.10.01 |