Algorithm/백준 알고리즘

백준_2257 화학식량(자바) / 문자열

미스터로즈 2021. 11. 4. 09:24

시간&메모리 제한

 

문제

 

입력&출력

 

문제풀이

package com.Back;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Back_2257 {

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String chem = br.readLine();
		int stack[] = new int[100];
		int tmp = 0;
		int cnt = 0;
		for (int i = 0; i < chem.length(); i++) {
			char c = chem.charAt(i);
			
			if(c=='H') {
				tmp=1;
				stack[cnt] +=1;
			}else if(c=='C') {
				tmp=12;
				stack[cnt] +=12;
			}else if(c=='O') {
				tmp=16;
				stack[cnt] +=16;
			}else if(c=='(') {
				stack[++cnt]=0;
			}else if(c==')') {
				tmp = stack[cnt--];
				stack[cnt]+=tmp;
			}else if(c>'1' && c<='9') {
				stack[cnt]+=tmp*(c-'1');
			}
		}
		System.out.println(stack[0]);
	}
}

 

※ 내 생각

이 문제는 문자열 문제입니다.
문자열의 각 문자에 따라서 처리를 진행하면 해결할 수 있습니다.

Stack로 관리할 수 있지만, 간단하게 배열을 만들어서 관리를 했습니다.