문제. 소괄호 사이에 모든 문자를 제거하고 남은 문자를 출력하시오
입력예시
((KDS)(SK)FD)FKD(FK)DJG(DF)
답 : FKDDJG
나의 답변 - Stack보다 int를 사용하는 것이 메모리 사용에 더 효율적이다. Stack은 메모리에 계속 적재되기때문
public class Main {
public String solution(String str) {
String answer = "";
int cnt=-1;
for( char x : str.toCharArray()) {
if(x=='(') {
cnt++;
} else if(x==')') {
cnt--;
} else {
if(cnt<0) answer+=x;
}
}
return answer;
}
public static void main(String[] args) {
Main T = new Main();
Scanner sc = new Scanner(System.in);
String str=sc.next();
System.out.print(T.solution(str));
}
}
Stack을 사용한 답변
public class Main {
public String solution(String str) {
String answer = "";
Stack<Character> stack = new Stack<>();
for( char x : str.toCharArray()) {
if(x==')') {
while(stack.pop()!='(');
}else {
stack.push(x);
}
}
for( int i=0; i<stack.size(); i++ ) {
answer+=stack.get(i);
}
return answer;
}
public static void main(String[] args) {
Main T = new Main();
Scanner sc = new Scanner(System.in);
String str=sc.next();
System.out.print(T.solution(str));
}
}
- 닫는 괄호를 만나면 여는 괄호를 만날때까지 pop하기
- pop()은 Stack에서 제일 상단의 값을 꺼내고 return 한다.
- Stack의 길이값을 알고 싶다면 stack.size() 사용
- Stack에서 해당 값을 꺼내고 싶다면 stack.get() 사용
'코딩테스트 및 알고리즘' 카테고리의 다른 글
후위표기식 계산 (0) | 2024.01.16 |
---|---|
Stack (0) | 2024.01.14 |
올바른 괄호 (0) | 2024.01.10 |
트리 (0) | 2024.01.08 |
N장의 카드에서 3장 뽑고 그 합이 k번째로 큰 수 구하기 (0) | 2024.01.07 |