• Home
  • About
    • on Weekend photo

      on Weekend

      𝙎𝙩𝙪𝙙𝙮𝙞𝙣𝙜

    • Learn More
    • Instagram
    • Github
  • Archive
    • All Posts
    • All Tags
    • All Categories
  • Categories
    • Problem Solving
    • TIL
    • Study
    • Etc
    • 필사
  • Projects

JAVA 코딩테스트를 위한 간단 정리

03 Apr 2021

문자열을 문자 배열로 바꾸기

String s = "1 2 3 4";
String[] splitString = s.split(" ");

문자를 int로 바꾸기

int min, max, n;
String s = "1 2 3 4";
String[] tmp = s.split(" ");
min = max = Integer.parseInt(tmp[0]);

배열 정렬하기

int[] A = {1,4,2};
int[] B = {5,4,4};
Arrays.sort(A);
Arrays.sort(B, Collections.reverseOrder());

Stack 사용하기

import java.util.Stack;
public class Solution {
    public static void main(String[] args) {
        Stack stack = new Stack();
        stack.push(3);
        stack.push(2);
        System.out.println(stack.pop());
        System.out.println(stack.peek());
    }
}

배열 길이를 모르겠을 때

int[] answer = new int[2];

String에서 특정 문자만 char type으로 가져올 때

String word = words[i];
first = word.charAt(0);
last = word.charAt(word.length() - 1);

길이를 모르는 배열 ArrayList 사용하기

List<String> list = new ArrayList<>();
list.add(word);

ArrayList 안에 어떤 원소의 존재 여부 find

List<String> list = new ArrayList<>();
list.add(word);
if(list.contains(word)) continue;

자바의 자료형

참고 자료

  1. List
    • 중복 허용
    • 저장 순서 유지
    • 자동으로 인덱스가 부여되어 객체 검색, 삭제 가능함
    • 추가(add), 검색(contains), 삭제(remove) 가진다.

가령 ArrayList가 있다.

List<Type> list = new ArrayList<>(); //길이 존재X
List<Type> list = new ArrayList<Type>(n); //길이 존재
list.add("A");
list.get(0); // A
list.remove(0); // A 삭제
  1. Set
    • 중복 비허용
    • 저장 순서 비유지
    • 검색 불가능 (Iterator 사용해야함)
Set<String> setExample = new Set<>();
...
Iterator<String> iterator = setExample.iterator();
while(iterator.hasNext()) {
    String getin = iterator.next();
}
  1. Map
    • key, value로 구성 (‘=. 파이썬 딕셔너리)
    • key는 중복 저장 불가능하다.
    • value 중복 저장 시, 기존 값은 없어지고 새로운 값으로 대체됨
Map<K,V> map = new HashMap<K,V>();
map.put("Key", "Value");
if(map.containsKey("key")) {
    map.remove("key");
}

문자열 더하는 작업에는 StringBuilder

StringBuilder answer = new StringBuilder();
String firstStr = s.charAt(0) + ""; // ""를 더해 String으로
answer.append(firstStr.toUpperCase());

for(int i=1; i<s.length(); i++) { // 문자열을 순회하며
    String now = s.charAt(i) + ""; // 현재 char을 받아와서
    if(now.equals(' ')) answer.append(" ");
    else if(s.charAt(i - 1) == ' ') { // 직전이 공백이면
        answer.append(now.toUpperCase()); // 대문자로
    }
    else {
        answer.append(now.toLowerCase()); 
    }
    return answer.toString();
}


problem_solvingjava Share Tweet +1