๐ฉ๐ปProgramming/Coding Test
[C#] [BOJ#10828] ์คํ
taesooya
2022. 8. 13. 16:51
https://www.acmicpc.net/problem/10828
10828๋ฒ: ์คํ
์ฒซ์งธ ์ค์ ์ฃผ์ด์ง๋ ๋ช ๋ น์ ์ N (1 ≤ N ≤ 10,000)์ด ์ฃผ์ด์ง๋ค. ๋์งธ ์ค๋ถํฐ N๊ฐ์ ์ค์๋ ๋ช ๋ น์ด ํ๋์ฉ ์ฃผ์ด์ง๋ค. ์ฃผ์ด์ง๋ ์ ์๋ 1๋ณด๋ค ํฌ๊ฑฐ๋ ๊ฐ๊ณ , 100,000๋ณด๋ค ์๊ฑฐ๋ ๊ฐ๋ค. ๋ฌธ์ ์ ๋์์์ง
www.acmicpc.net
- ์คํ : ์ ๋ค๋ฆญ์ด ์๋ ๊ฐ์ฒด์ ๊ฐ๋จํ LIFO(Last In First Out: ๋ง์ง๋ง์ ๋ค์ด๊ฐ ๊ฒ๋ถํฐ ์ฌ์ฉ) ์ปฌ๋ ์ ์ ๋ํ๋ ๋๋ค.
- ๋ค์์คํ์ด์ค : System.Collections
My Solution
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int t = int.Parse(Console.ReadLine());
Stack<string> myStack = new Stack<string>();
for (int i = 0; i < t; i++)
{
string[] s = Console.ReadLine().Split();
StringBuilder sb = new StringBuilder();
string a = s[0];
if (a == "push")
{
myStack.Push(s[1]);
}
if (a == "pop")
{
sb.Append(myStack.Count != 0 ? myStack.Pop() : "-1");
Console.WriteLine(sb);
}
if (a == "size")
{
sb.Append(myStack.Count.ToString());
Console.WriteLine(sb);
}
if (a == "empty")
{
sb.Append(myStack.Count != 0 ? "0" : "1");
Console.WriteLine(sb);
}
if (a == "top")
{
sb.Append(myStack.Count == 0 ? "-1" : myStack.Peek());
Console.WriteLine(sb); ;
}
}
}
}
}
ShortCode
- appendline์ ์ฐจ์ด๋ฅผ ๋ชจ๋ฅด๊ฒ ์ - ์ถ๋ ฅ์ด ๋ค๋ฅด๊ธด ํจ ;; ์?
- ์ผํญ์ฐ์ฐ์ ์ฌ์ฉํด์ ์งง๊ฒ ๊ตฌํ
using System;
using System.Collections.Generic;
using System.Linq;
var n = int.Parse(Console.ReadLine()!);
var stack = new Stack<string>();
var output = new System.Text.StringBuilder();
foreach (var _ in Enumerable.Range(0, n))
{
var input = Console.ReadLine()!.Split();
switch (input[0])
{
case "push":
stack.Push(input[1]);
break;
case "pop":
output.AppendLine(stack.TryPop(out var pop) ? pop : "-1");
break;
case "size":
output.AppendLine(stack.Count.ToString());
break;
case "empty":
output.AppendLine(stack.Any() ? "0" : "1");
break;
case "top":
output.AppendLine(stack.TryPeek(out var peek) ? peek : "-1");
break;
}
}
Console.WriteLine(output.ToString());