예제
- Stack<Integer> st = new Stack<>(); //스택 객체생성
- st.push(1); //스택에 1 추가
- st.pop(); //스택 하나 꺼내기
- st.isEmpty() //스택이 비었는가 ture false
import java.util.Stack;
class Solution {
boolean solution(String s) {
boolean answer = true;
String res = "YES";
Stack<Integer> st = new Stack<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
st.push(1);
} else if (s.charAt(i) == ')') {
if (st.isEmpty()) {
answer = false;
break;
} else {
st.pop();
}
}
}
if(!st.isEmpty()) {
answer = false;
}
System.out.println(res);
return answer;
}
}
================================================================
Queue(보통 큐를 구현한 LinkedList사용)
.add(Object o)
//지정된 객체를 Queue에 추가한다. 성공하면true를 반환. 저장공간이 부족하면 IllegalStateException 발생
.remove()
//Queue에서 객체를 꺼내 반환, Object o 지정해서 꺼낼 수 있음
.offer(Object o)
Queue 객체를 저장. 성공하면 true 실패하면 false를 반환
.poll()
Queue에서 객체를 꺼내서 반환 비어있으면 null을 반환
.peek()
삭제없이 요소를 읽어 온다. Queue가 비어있으면 null 반환
import java.util.*;
class Solution {
public int solution(int cacheSize, String[] cities) {
int answer = 0;
// LRU
// 사용한지 가장 오래된 페이지를 대체
LinkedList<String> list = new LinkedList<String>();
if(cacheSize == 0){
return 5*cities.length;
}
for(String city : cities){
city = city.toUpperCase();
if(list.contains(city)){
answer += 1;
list.remove(list.indexOf(city));
list.offer(city);
} else {
if(list.size() == cacheSize){
list.poll();
}
answer += 5;
list.offer(city);
}
}
return answer;
}
}
================================================================
collection sort()
import java.util.*;
class Solution {
public String[] solution(String[] strings, int n) {
String[] answer = new String[strings.length];
ArrayList<Str> strs = new ArrayList<>();for(String string : strings) {
Str str = new Str(string, n);
strs.add(str);
}
Collections.sort(strs);
for(int i=0; i<answer.length; i++)
answer[i] = strs.get(i).s;
return answer;
}
public class Str implements Comparable<Str>
{
String s;
int n;
public Str(String s, int n) {
this.s = s;
this.n = n;
}
@Override
public int compareTo(Str arg0) {
if(s.charAt(n) > arg0.s.charAt(n))
return 1;
if(s.charAt(n) < arg0.s.charAt(n))
return -1;
for(int i=0; i<s.length(); i++) {
if(s.charAt(i) > arg0.s.charAt(i))
return 1;
else if(s.charAt(i) < arg0.s.charAt(i))
return -1;
}
return 0;
}
}
}
for 문을 통한 정렬
for(int a=N-1;a>=1;a--){
for(int b=N-1;b>=(N-a);b--){
if(fail[b-1]<fail[b] ){
double temp=fail[b-1];
fail[b-1]=fail[b];
fail[b]=temp;
int temp2=answer[b-1];
answer[b-1]=answer[b];
answer[b]=temp2;
}
}
}