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

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

 

4949๋ฒˆ: ๊ท ํ˜•์žกํžŒ ์„ธ์ƒ

ํ•˜๋‚˜ ๋˜๋Š” ์—ฌ๋Ÿฌ์ค„์— ๊ฑธ์ณ์„œ ๋ฌธ์ž์—ด์ด ์ฃผ์–ด์ง„๋‹ค. ๊ฐ ๋ฌธ์ž์—ด์€ ์˜๋ฌธ ์•ŒํŒŒ๋ฒณ, ๊ณต๋ฐฑ, ์†Œ๊ด„ํ˜ธ("( )") ๋Œ€๊ด„ํ˜ธ("[ ]")๋“ฑ์œผ๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ์œผ๋ฉฐ, ๊ธธ์ด๋Š” 100๊ธ€์ž๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™๋‹ค. ์ž…๋ ฅ์˜ ์ข…๋ฃŒ์กฐ๊ฑด์œผ๋กœ ๋งจ ๋งˆ

www.acmicpc.net


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

๐ŸŽจ Go

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

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

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

	for {
		var input string
		input, _ = reader.ReadString('\n') // ๊ณต๋ฐฑ ํฌํ•จํ•˜์—ฌ ์ž…๋ ฅ ๋ฐ›๊ธฐ ์œ„ํ•ด ReadString() ์‚ฌ์šฉ
		convInput := strings.ReplaceAll(input, "\n", "")
		if convInput == "." {
			break
		}
		fmt.Fprintln(writer, isBalanced(convInput))
	}
}

func isBalanced(input string) (result string) {
	var stack []string
	for _, v := range input {
		strV := string(v)
		if strV == "(" || strV == "[" {
			stack = append(stack, strV)
		} else if strV == ")" {
			if len(stack) > 0 && stack[len(stack)-1] == "(" {
				stack = stack[:len(stack)-1]
			} else {
				return "no"
			}
		} else if strV == "]" {
			if len(stack) > 0 && stack[len(stack)-1] == "[" {
				stack = stack[:len(stack)-1]
			} else {
				return "no"
			}
		} else {
			continue
		}
	}
	if len(stack) > 0 {
		return "no"
	}
	return "yes"
}

๐ŸŽจ Python3

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

def is_balanced(input):
    stack = []
    for v in input:
        if v == "(" or v == "[":
            stack.append(v)
        elif v == ")":
            if len(stack) > 0 and stack[-1] == "(":
                stack = stack[:-1]
            else:
                return "no"
        elif v == "]":
            if len(stack) > 0 and stack[-1] == "[":
                stack = stack[:-1]
            else:
                return "no"
        else:
            continue
    if len(stack) > 0:
        return "no"
    return "yes"

if __name__ == "__main__":
    while True:
        input = sys.stdin.readline().rstrip('\n')
        if input == ".":
            break
        print(is_balanced(input))
728x90
๋Œ“๊ธ€