[Javaアルゴリズム]5-2.かっこ文字の削除


🌼 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);
    }
}