[Javaアルゴリズム]5-2.かっこ文字の削除
8020 ワード
🌼 Problem
🍔 Solution 1
import java.util.Iterator;
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void Solution(String str){
Stack<Character> st = new Stack<>();
char[] c = str.toCharArray();
for(char x : str.toCharArray()){
if(x!=')'){
st.push(x);
}else{
while(st.peek()!='('){
st.pop();
}
// '(' 꺼내기 위함
st.pop();
}
}
Iterator iter = st.iterator();
while(iter.hasNext()){
System.out.print(iter.next());
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.next();
Solution(input);
}
}
🍪 講師ソリューション-大きな違いはありません!
import java.util.Iterator;
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void Solution(String str){
Stack<Character> st = new Stack<>();
for(char x : str.toCharArray()){
if(x==')'){
while(st.pop()!='('); // st.pop()은 꺼내고 return까지!
}else{
st.push(x); // '(', 알파벳은 push
}
}
for(int i =0 ; i<st.size(); i++){
System.out.print(st.get(i));
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.next();
Solution(input);
}
}
Reference
この問題について([Javaアルゴリズム]5-2.かっこ文字の削除), 我々は、より多くの情報をここで見つけました https://velog.io/@dingdoooo/Java알고리즘-5-2.-괄호문자제거テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol