Coding Test - cpp/Stack, Queue
[프로그래머스 lv 1 ] - [1차] 다트 게임
에드윈H
2021. 10. 1. 00:26
https://programmers.co.kr/learn/courses/30/lessons/17682
#include <string>
#include <stack>
#include <cctype>
using namespace std;
int solution( string dartResult ) {
int answer = 0;
int size = dartResult.size();
stack<int> st;
int score = 0;
for( int i = 0; i < size; i++ )
{
if( dartResult[i] == 'D' || dartResult[i] == 'S' || dartResult[i] == 'T' )
{
if( dartResult[i] == 'D' )
{
st.push( score * score );
}
else if( dartResult[i] == 'T' )
{
st.push( score * score * score );
}
else
{
st.push( score );
}
}
else if( dartResult[i] == '*' || dartResult[i] == '#' )
{
if( dartResult[i] == '*' )
{
if( st.empty() )
{
int cur = st.top();
st.pop();
cur *= 2;
st.push( cur );
}
else
{
int cur = st.top();
st.pop();
int cur2 = st.top();
st.pop();
cur *= 2;
cur2 *= 2;
st.push( cur2 );
st.push( cur );
}
}
else{
int cur = st.top();
st.pop();
cur *= -1;
cout << cur << endl;
st.push( cur );
}
}
else
{
string num;
while( isdigit( dartResult[i] ) != 0 )
{
num += dartResult[i++];
}
score = stoi( num );
i--;
}
}
while( !st.empty() )
{
answer += st.top();
st.pop();
}
return answer;
}
switch문으로 수정
#include <string>
#include <stack>
#include <cctype>
using namespace std;
int solution( string dartResult ) {
int answer = 0;
int size = dartResult.size();
stack<int> st;
int score = 0;
for( int i = 0; i < size; i++ )
{
char dart = dartResult[i];
switch( dart )
{
case 'S':
st.push( score );
break;
case 'D':
st.push( score * score );
break;
case 'T':
st.push( score * score * score );
break;
case '*':
if( st.empty() ) //비었을경우 한개의 값만 두배
{
int cur = st.top();
st.pop();
cur *= 2;
st.push( cur );
}
else
{
int cur = st.top();
st.pop();
int cur2 = st.top();
st.pop();
cur *= 2;
cur2 *= 2;
st.push( cur2 );
st.push( cur );
}
break;
case '#':
{
int cur = st.top();
st.pop();
cur *= -1;
st.push( cur );
break;
}
default: //점수일 경우
{
string num;
while( isdigit( dartResult[i] ) != 0 ) //0이 아니면 문자열
{
num += dartResult[i++];
}
score = stoi( num );
i--;
break;
}
}
}
//모든 stack의 값 계산
while( !st.empty() )
{
answer += st.top();
st.pop();
}
return answer;
}