알고리즘
-
프로그래머스 - 가장 가까운 같은 글자알고리즘 2024. 4. 12. 00:30
import java.util.*; class Solution { public int[] solution(String s) { int[] answer = new int[s.length()]; char[] arr = s.toCharArray(); Map map = new HashMap(); for(int i = 0; i < arr.length; i++) { if(!map.containsKey(arr[i])){ answer[i] = -1; map.put(arr[i], i); }else { int index = map.get(arr[i]); answer[i] = i - index; map.put(arr[i], i); } } return answer; } } String 을 char 배열로 변환하여, 각 글자를..
-
프로그래머스 - 최소 직사각형알고리즘 2024. 4. 12. 00:05
class Solution { public int solution(int[][] sizes) { int width = 0; // 큰 값 int height = 0; // 작은 값 for(int[] card : sizes) { int card_width = Math.max(card[0], card[1]); int card_height = Math.min(card[0], card[1]); if(width < card_width) width = card_width; if(height < card_height) height = card_height; } return width * height; } } 명함은 회전이 가능하기 때문에 큰 값을 가로로 작은 값을 세로로 정하여 값을 비교하여 넓이를 구했습니다.
-
프로그래머스 - 시저 암호알고리즘 2024. 4. 11. 23:24
class Solution { public String solution(String s, int n) { StringBuilder sb = new StringBuilder(); for(char c : s.toCharArray()) { if(c >= 'a' && c 'z') ? (char)(c - 26 + n) : (char)(c + n); sb.append(c); } else if(c >= 'A' && c 'Z' ? (char)(c - 26 + n) : (char)(c + n); sb.append(c); } else { sb.append(" "); } } return sb.toString(); } } 소문자, 대문자인지 판별 후 n을 더했을 때 범위를 넘어선다면 알파벳의 길이인 26을 빼서 다시 a, A..
-
프로그래머스 - 최빈값 구하기알고리즘 2024. 4. 6. 21:41
import java.util.*; class Solution { public int solution(int[] array) { int answer = 0; int frequency = 0; // 최대 빈도수 boolean overlap = false; // 중복여부 Map map = new HashMap(); for(int num : array) { if(!map.containsKey(num)) map.put(num, 1); else { int cnt = map.get(num); map.put(num, cnt + 1); } } for(int key : map.keySet()) { if(frequency == map.get(key)) overlap = true; if(frequency < map.get(..
-
프로그래머스 - 안전지대알고리즘 2024. 4. 5. 20:54
class Solution { public int solution(int[][] board) { int answer = 0; for(int i = 0; i < board.length; i++) { for(int j = 0; j < board.length; j++) { if(board[i][j] == 1) danger(board, i, j); } } for(int i = 0; i < board.length; i++) { for(int j = 0; j < board.length; j++) { if(board[i][j] == 0) answer++; } } return answer; } public void danger(int[][] board, int x, int y) { for(int i = -1; i
-
프로그래머스 - 다항식 더하기알고리즘 2024. 4. 5. 01:29
import java.util.*; class Solution { public String solution(String polynomial) { StringBuilder sb = new StringBuilder(); int var = 0; int con = 0; List variables = new ArrayList(); List constants = new ArrayList(); for(String s : polynomial.split(" ")) { if(s.contains("x")) { s = s.replace("x", ""); if(s.equals("")) variables.add(1); else variables.add(Integer.parseInt(s)); } else if(s.contains(..