[白俊]4949号:均衡の世界
白駿4949号:バランスのとれた世界
入力例:
So when I die (the [first] I will see in (heaven) is a score list).
[ first in ] ( first out ).
Half Moon tonight (At least it is better than no Moon at all].
A rope may form )( a trail in a maze.
Help( I[m being held prisoner in a fortune cookie factory)].
([ (([( [ ] ) ( ) (( ))] )) ]).
.
.
出力例:
yes
yes
no
no
no
yes
yes
スタック:後入先出(Last In First Out)を使用してpopを実行すると、後押しのデータが先に表示されます. "."表示される前に入力を受け入れます. 文字列を1文字ずつ文字に変換し、かっこかかっこか、左かっこか右かっこかを判断します.
括弧が の場合、スタック にプッシュする.が括弧の場合は、括弧のペア が必要です.の括弧にスペースまたは括弧がない場合は、「no」 を返します.
1.問題の説明
入力例:
So when I die (the [first] I will see in (heaven) is a score list).
[ first in ] ( first out ).
Half Moon tonight (At least it is better than no Moon at all].
A rope may form )( a trail in a maze.
Help( I[m being held prisoner in a fortune cookie factory)].
([ (([( [ ] ) ( ) (( ))] )) ]).
.
.
出力例:
yes
yes
no
no
no
yes
yes
2.問題を解く
スタック:後入先出(Last In First Out)を使用してpopを実行すると、後押しのデータが先に表示されます.
while(true) {
s=sc.nextLine();
if(s.equals(".")) {
break;
}
}
括弧が
if(c=='('||c=='[') {
stack.push(c);
}
if(stack.isEmpty()||stack.peek()!='(') {
return "no";
}
else {
stack.pop();
}
if(stack.isEmpty()||stack.peek()!='[') {
return "no";
}
else {
stack.pop();
}
コード#コード#import java.util.*;
public class No_4949 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String s="";
while(true) {
s=sc.nextLine();
if(s.equals(".")) {
break;
}
System.out.println(solution(s));
}
}
public static String solution(String s) {
Stack<Character> stack =new Stack<>();
for(int i=0;i<s.length();i++) {
char c=s.charAt(i);
if(c=='('||c=='[') {
stack.push(c);
}
else if(c==')') {
if(stack.isEmpty()||stack.peek()!='(') {
return "no";
}
else {
stack.pop();
}
}
else if(c==']') {
if(stack.isEmpty()||stack.peek()!='[') {
return "no";
}
else {
stack.pop();
}
}
}
if(stack.isEmpty()) {
return "yes";
}
else {
return "no";
}
}
}
実行結果Reference
この問題について([白俊]4949号:均衡の世界), 我々は、より多くの情報をここで見つけました https://velog.io/@jay2721/백준-4949번-균형잡힌-세상テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol