ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป ๋ฌธ์ œ

 

9012๋ฒˆ: ๊ด„ํ˜ธ

๊ด„ํ˜ธ ๋ฌธ์ž์—ด(Parenthesis String, PS)์€ ๋‘ ๊ฐœ์˜ ๊ด„ํ˜ธ ๊ธฐํ˜ธ์ธ ‘(’ ์™€ ‘)’ ๋งŒ์œผ๋กœ ๊ตฌ์„ฑ๋˜์–ด ์žˆ๋Š” ๋ฌธ์ž์—ด์ด๋‹ค. ๊ทธ ์ค‘์—์„œ ๊ด„ํ˜ธ์˜ ๋ชจ์–‘์ด ๋ฐ”๋ฅด๊ฒŒ ๊ตฌ์„ฑ๋œ ๋ฌธ์ž์—ด์„ ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ ๋ฌธ์ž์—ด(Valid PS, VPS)์ด๋ผ๊ณ 

www.acmicpc.net


โœ๐Ÿป ํ’€์ด

๐ŸŽจ Go

// https://www.acmicpc.net/problem/9012
// ์ฃผ์–ด์ง„ ๋ฌธ์ž์—ด์ด ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ์—ด์ธ์ง€ ํŒ๋‹จํ•˜๋Š” ๋ฌธ์ œ
package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	var t int
	fmt.Fscanln(reader, &t)

	for i := 0; i < t; i++ {
		var inputStr string
		fmt.Fscanln(reader, &inputStr)
		fmt.Fprintln(writer, isVPS(inputStr))
	}
}

func isVPS(inputStr string) string {
	var open, close int
	for _, v := range inputStr {
		if string(v) == "(" {
			open++
		} else if string(v) == ")" {
			close++
		}
		if open < close { // ๋‹ซํžŒ ๊ด„ํ˜ธ ๊ฐœ์ˆ˜๊ฐ€ ๋” ๋งŽ์•„์ง€๋ฉด "NO" ๋ฆฌํ„ด
			return "NO"
		}
	}
	if open != close { // ์ตœ์ข… ๊ด„ํ˜ธ ๊ฐœ์ˆ˜๊ฐ€ ๋‹ค๋ฅด๋ฉด "NO" ๋ฆฌํ„ด
		return "NO"
	}
	return "YES"
}


// // ์Šคํƒ์œผ๋กœ ํ’€๊ธฐ
// func isVPS2(inputStr string) string {
// 	var stack []string
// 	for _, v := range inputStr {
// 		strValue := string(v)
// 		if strValue == "(" {
// 			stack = append(stack, strValue)
// 		} else if strValue == ")" {
// 			if len(stack) > 0 {
// 				stack = stack[:len(stack)-1]
// 			} else {
// 				return "NO"
// 			}
// 		}
// 	}
// 	if len(stack) > 0 {
// 		return "NO"
// 	}
// 	return "YES"
// }

๐ŸŽจ Python3

# https://www.acmicpc.net/problem/9012
# ์ฃผ์–ด์ง„ ๋ฌธ์ž์—ด์ด ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ์—ด์ธ์ง€ ํŒ๋‹จํ•˜๋Š” ๋ฌธ์ œ
import sys

def is_vps(input_str):
    open_count, close_count = 0, 0
    for s in input_str:
        if s == "(":
            open_count += 1
        elif s == ")":
            close_count += 1
        if open_count < close_count:
            return "NO"
    if open_count != close_count:
        return "NO"
    return "YES"

if __name__ == "__main__":
    t = int(sys.stdin.readline())
    for i in range(t):
        print(is_vps(sys.stdin.readline()))
728x90
๋Œ“๊ธ€