2023. 10. 30. 14:24ใ์ธํ๋ฐ/์๋ฐ ์๊ณ ๋ฆฌ์ฆ ๋ฌธ์ ํ์ด ์ ๋ฌธ : ์ฝ๋ฉํ ์คํธ ๋๋น
https://hyejin.tistory.com/1234
-> ์ด์ ๋ฌธ์ ํ์ด
4. ํ์์ ์ฐ์ฐ (postfix)
์ค๋ช
ํ์์ฐ์ฐ์์ด ์ฃผ์ด์ง๋ฉด ์ฐ์ฐํ ๊ฒฐ๊ณผ๋ฅผ ์ถ๋ ฅํ๋ ํ๋ก๊ทธ๋จ์ ์์ฑํ์ธ์.
๋ง์ฝ 3*(5+2)-9 ์ ํ์์ฐ์ฐ์์ผ๋ก ํํํ๋ฉด 352+*9- ๋ก ํํ๋๋ฉฐ ๊ทธ ๊ฒฐ๊ณผ๋ 12์ ๋๋ค.
์ ๋ ฅ
์ฒซ ์ค์ ํ์์ฐ์ฐ์์ด ์ฃผ์ด์ง๋๋ค. ์ฐ์ฐ์์ ๊ธธ์ด๋ 50์ ๋์ง ์์ต๋๋ค.
์์ 1~9์ ์ซ์์ +, -, *, / ์ฐ์ฐ์๋ก๋ง ์ด๋ฃจ์ด์ง๋ค.
์ถ๋ ฅ
์ฐ์ฐํ ๊ฒฐ๊ณผ๋ฅผ ์ถ๋ ฅํฉ๋๋ค.
์์ ์ ๋ ฅ 1
352+*9-
์์ ์ถ๋ ฅ 1
12
๋ฌธ์ ํ์ด 1
public int solution(String str)
{
int answer = 0;
Stack<Integer> stack = new Stack<>();
for (char c : str.toCharArray())
{
if (Character.isDigit(c)) {
stack.push((int) c - 48);
}else {
int a = stack.pop();
int b = stack.pop();
switch (c) {
case '+':
answer = b + a ;
break;
case '-':
answer = b - a ;
break;
case '*':
answer = b * a;
break;
case '/':
answer = b / a;
break;
}
stack.push(answer);
answer =0;
}
}
return stack.get(0);
}
๐ฉ๐ป : ์ด ๋ฌธ์ ๋ ์ซ์์ผ ๋๋ stack์ ๋ฃ์ด๋๋ค๊ฐ ์ฐ์ฐ์๋ฅผ ๋ง๋๋ฉด stack์์ ๋๊ฐ์ ์ซ์๋ฅผ ๊บผ๋ด์ ์ฐ์ฐํ๊ณ , ๊ทธ ๊ฒฐ๊ณผ๋ฅผ ๋ค์ stack์ ๋ฃ์ด๋๋ฉด ๋๋ค.
๊ทธ๋์ ์ฐ์ Character.isDigit() ๋ฉ์๋๋ฅผ ์ฌ์ฉํด์ ๋ฌธ์๊ฐ ์ซ์์ด๋ฉด stack.pushํ๋๋ฐ ์ด๋, ๋ฌธ์ c ๊ฐ์ ๊ทธ๋๋ก ๋ฃ์ผ๋ฉด c๊ฐ '3' ์ผ๋ stack์ 51 ๊ฐ์ด stack์ ๋ด๊ธด๋ค. ๊ทธ๋ฌ๋ฏ๋ก '0'์ ๊ฐ์ ํด๋นํ๋ 48์ ๋นผ์ค์ผ ํ๋ค.
๊ทธ ๋ค์ ์ฐ์ฐ์์ด๋ฉด ์ด์ stack์์ 2๊ฐ์ ๊ฐ์ ๊บผ๋ด์ a, b ๋ณ์์ ๋ด์๋ค.
๊ทธ ๋ค์ +, -, *, / ์ฐ์ฐ์์ ํด๋นํ๋ ์ฐ์ฐ์ ์ํํ๋ฉด ๋๋๋ฐ ์ด๋, ํ์ ์ฐ์ฐ์ด๊ธฐ ๋๋ฌธ์ b๊ฐ ๋จผ์ ๊ณ์ฐ๋์ด์ผ ํ๋ค.
๊ทธ ๋ค์ ์ด ์ฐ์ฐ ๊ฒฐ๊ณผ๋ฅผ stack์ pushํด์ฃผ๋ฉด ๋๊ณ , answer ๋ฅผ 0์ผ๋ก ์ด๊ธฐํํด์ค๋ค. (์ฌ์ค answer ์ด๊ธฐํ ์ด๋ฐ ๊ณผ์ ์์ด ๋ฐ๋ก stack์ ๋ฃ์ผ๋ฉด ๋๋ ๊ฒ์..!)
๊ทธ ๋ค์ ๋งจ ๋ง์ง๋ง๊น์ง stack์ ๋จ์์๋ ๊ฐ์ด ์ต์ข ์ฐ์ฐ ๊ฒฐ๊ณผ์ด๊ธฐ ๋๋ฌธ์ stack.get(0) ๊ฐ์ ๊บผ๋ด์ ๋ฆฌํดํ๋ฉด ๋๋ค.
๋ฌธ์ ํ์ด 2
public int solution2(String str)
{
Stack<Integer> stack = new Stack<>();
for (char c : str.toCharArray())
{
if (Character.isDigit(c)) {
stack.push(c - 48);
}else
{
int rt = stack.pop();
int lt = stack.pop();
if (c == '+') {
stack.push(lt + rt);
}
else if (c == '-') {
stack.push(lt - rt);
}
else if (c == '*') {
stack.push(lt * rt);
}
else if (c == '/') {
stack.push(lt / rt);
}
}
}
return stack.get(0);
}
๐พ : ๊ฐ์ฌ๋๋ ๋๋ ๋์ผํ ๋ฐฉ์์ผ๋ก ํ์๋๋ฐ lt, rt ๋ก ๋ณ์ ์ด๋ฆ์ ๋์ด ์ข ๋ ์ฝ๊ฒ ๊ตฌ๋ถํ ์ ์๊ฒ ํ๋ค.
๊ทธ ๋ค์, stack์ ๋ฐ๋ก ์ฐ์ฐ ๊ฒฐ๊ณผ๋ฅผ push ํ๊ณ , ๊ทธ ๋ค์ stack.get(0) ์ ๋ฆฌํดํด์คฌ๋ค.