[๊ธฐ๋ณธ] ์คํ ์๋ฃ๊ตฌ์กฐ ํ์ฉ
์คํ์ ํ์ฉํด์ผํ๋ ๋ฌธ์
์คํ์ ํ์ฉํด์ผ ํ๋ ๊ฒฝ์ฐ๋ ๋ณดํต ์ง์ ์ง๋ ๋ฌธ์ ์ ๋๋ค. ๋จ๋ ๊ฐ ๋ฐ๋ณต๋ผ์ ๋ํ๋๊ฑฐ๋, ๋๋ฌผ ๋ฑ๋ฑ ๊ต์ฐจ๋ก ๋ฐ๋ณต๋๋ ์ํฉ์์ ์ง์ ๋ง์ถฐ์ผํ๋ ๊ฒฝ์ฐ์ ์ฌ์ฉํฉ๋๋ค. ๊ทธ ์ค ๋ํ์ ์ธ ๋ฌธ์ ๋ ๊ดํธ์ ๋๋ค. ๊ดํธ๋ ๋ฐ๋์ ์ฌ๋ ๊ดํธ์ ๋ซ๋ ๊ดํธ๊ฐ ์ง์ด ์ด๋ฃจ์ด์ ธ์ผ๊ฒ ์ฃ . ๊ทธ๋ ์ง ์์ผ๋ฉด, ๋ฌธ์ ๊ฐ ๋ฐ์ํฉ๋๋ค. jsonํ์ผ์ ๋ถ์ํ ๋๋ ๊ดํธ์ ์ฌ๋ซ์์ ๋ถ์ํด์ผ ํฉ๋๋ค. ์ค์ฒฉ์ผ๋ก ๊ฐ์ฒด๊ฐ ์์ ์ ์๊ณ ๊ทธ ๋ด๋ถ์ array๊น์ง ์๋ค๋ฉด, ํจ์ ์ฝ ์คํ ์ฒ๋ผ ๋ด๋ถ๋ก ๋ค์ด๊ฐ๋ค๊ฐ ๋์ฌ๋ ๋ซ๋ ๊ดํธ๋ฅผ ๊ธฐ์ค์ผ๋ก ๋น ์ ธ๋์ค๊ฒ ๋ฉ๋๋ค.
๋ฌธ์ ํ๊ธฐ
๋ฐฑ์ค 9012: ๊ดํธ(๋งํฌ)
ํ์ด
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <stack>
using namespace std;
int main()
{
int count;
cin >> count;
for (int i = 0; i < count; i++)
{
string str;
cin >> str;
stack<int> s;
bool error = false;
for (int j = 0; j < str.size(); j++)
{
if (str[j] == '(')
s.push(str[j]);
else
{
if (s.empty())
{
error = true;
printf("NO\n");
break;
}
s.pop();
}
}
if (!error)
printf("%s\n", s.empty() ? "YES" : "NO");
}
}
์ฌ๋ ๊ดํธ๊ฐ ๋์ค๋ฉด ์คํ์ ๋ฃ๊ณ , ๋ซ๋ ๊ดํธ๊ฐ ๋์ค๋ฉด ์คํ์์ ๋บ๋๋ค. ๋ซ๋ ๊ดํธ ์ฐจ๋ก์์ ์คํ์ด ๋น์ด์์ผ๋ฉด ๋ซ๋ ๊ดํธ๊ฐ ๋ ๋ง์์, ๋ฌธ์ ๊ฐ ์๋ ๊ฒฝ์ฐ์ ๋๋ค. ๋ฐ๋๋ก ๋ชจ๋ ๋ฌธ์์ด์ ์ํํ๋๋ฐ ์คํ์ด ๋น์ด์์ง ์๋ค๋ฉด ์ฌ๋ ๊ดํธ๊ฐ ๋ ๋ง์ ๊ฒฝ์ฐ์ ๋๋ค.
์คํ์ ์ฐ์ง ์๋ ํ์ด
#include <iostream>
#include <stack>
int main()
{
int T;
std::cin >> T;
std::string PS;
int count;
for (int i = 0; i < T; i++)
{
std::cin >> PS;
count = 0;
for (int j = 0; j < PS.size(); j++)
{
if (PS[j] == '(')
count++;
else
count--;
if (count < 0)
break;
}
if (count == 0)
std::cout << "YES\n";
else
std::cout << "NO\n";
}
}
๋ฌผ๋ก ์คํ์ ์ฐ์ง ์๊ณ , count๋ฅผ ํ์ฉํ ์๋ ์์ต๋๋ค. ๊ดํธ๋ฌธ์ ์ฒ๋ผ ์ง๊ด์ ์ธ ๋ฌธ์ ๋ ๋ค๋ฅธ ๋ฐฉ๋ฒ์ผ๋ก ์ถฉ๋ถํ ํ์ง๋ง, DFS์ ๊ฐ์ ๋ฌธ์ ๊ฐ ๋์ค๋ฉด ์คํ์ ํ์ฉ๋๊ฐ ๋ ์ฌ๋ผ๊ฐ๋๋ค.