글
프로그래머스 C# 올바른 괄호(시간 최소화, 괄호 알고리즘, JAVA)
프로그래밍
2023. 1. 21. 14:34
728x90
SMALL
using System;
public class Solution {
public bool solution(string s) {
int count = 0;
for(int i = 0;i<s.Length;i++)
{
count = s[i] == '(' ? count+1 : count-1;
// if/else문으로 하면 시간초과라고 안된다. 배열에서 (면 카운트를 플러스, 아니면 카운트를 마이너스
if(count < 0)
{
return false;
// 맨 처음에 count가 -1이하가 되면 바로 false를 반환하게 한다. )가 앞에 나오면 거기서 게임이 끝난 것이기 때문에 시간을 절약할 수 있기도 하다.
// 앞에서 count가 -1이 되면 (가 있어도 해결이 안되니까, 예를 들어 )(면 에러 그렇게 되게 코드가 되어 있다.
}
}
return count == 0;
}
}
/////
자바
import java.util.Stack;
class Solution {
boolean solution(String s) {
boolean answer = true;
String res = "YES";
Stack<Integer> st = new Stack<>();
for (int i = 0; i < s.length(); i++)
{
if (s.charAt(i) == '(')
{
st.push(1);
}
else if (s.charAt(i) == ')')
{
if (st.isEmpty())
{
answer = false;
break;
}
else
{
st.pop();
}
}
}
if(!st.isEmpty())
{
answer = false;
}
System.out.println(res);
return answer;
}
}
class Solution {
boolean solution(String s) {
boolean answer = false;
int count = 0;
for(int i = 0; i<s.length();i++)
{
if(s.charAt(i) == '(')
{
count++;
}
if(s.charAt(i) == ')')
{
count--;
}
if(count < 0)
{
break;
}
}
if(count == 0)
{
answer = true;
}
return answer;
}
}
728x90
'프로그래밍' 카테고리의 다른 글
프로그래머스 C# 2016년(int형 배열 생성, Datetime, JAVA) (0) | 2023.01.21 |
---|---|
프로그래머스 C# 두 정수 사이의 합(삼항연산자, JAVA) (0) | 2023.01.21 |
프로그래머스 C# 가운데 글자(string 몇 번째 문자 가져오기, JAVA) (0) | 2023.01.21 |
프로그래머스 C# 평행(GetLength, Distinct, float-소수, Count, JAVA) (0) | 2023.01.21 |
프로그래머스 C# 크기가 작은 부분 문자열(long.Parse, JAVA parseLong, substring) (0) | 2023.01.21 |