📝문제

📝알고리즘
//단어의 수 N 입력받고 다음과 같은 함수 작성
//A와 B로 이루어진 단어의 문자들을 순회하면서
//스택이 비어있지 않고 스택 최상단의 문자와 현재 문자가 일치하는 경우 스택에서 꺼내고
//그렇지 않으면 현재 문자를 스택에 넣는 것을 반복함
//다 순회한 후에 스택이 비어있으면 true를 반환함
//이 함수를 통해 좋은 단어 개수를 셈
//개수 출력
📝구현
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args)throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int N= Integer.parseInt(br.readLine());
int count=0;
for(int i=0; i<N;i++){
String alpha=br.readLine();
if(isGoodWord(alpha)){
count++;
}
}
System.out.print(count);
}
public static boolean isGoodWord(String alpha){
Stack<Character> stack=new Stack<>();
for(char c: alpha.toCharArray()){
if(!stack.isEmpty() && stack.peek()==c){
stack.pop();
}
else{
stack.push(c);
}
}
return stack.isEmpty();
}
}
📌기록하고 싶은 내용
알고리즘이 복잡해지면 함수로 따로 분리해서 문제를 더 명확히 구조화할 수 있음!