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

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

 

10799๋ฒˆ: ์‡ ๋ง‰๋Œ€๊ธฐ

์—ฌ๋Ÿฌ ๊ฐœ์˜ ์‡ ๋ง‰๋Œ€๊ธฐ๋ฅผ ๋ ˆ์ด์ €๋กœ ์ ˆ๋‹จํ•˜๋ ค๊ณ  ํ•œ๋‹ค. ํšจ์œจ์ ์ธ ์ž‘์—…์„ ์œ„ํ•ด์„œ ์‡ ๋ง‰๋Œ€๊ธฐ๋ฅผ ์•„๋ž˜์—์„œ ์œ„๋กœ ๊ฒน์ณ ๋†“๊ณ , ๋ ˆ์ด์ €๋ฅผ ์œ„์—์„œ ์ˆ˜์ง์œผ๋กœ ๋ฐœ์‚ฌํ•˜์—ฌ ์‡ ๋ง‰๋Œ€๊ธฐ๋“ค์„ ์ž๋ฅธ๋‹ค. ์‡ ๋ง‰๋Œ€๊ธฐ์™€ ๋ ˆ์ด์ €

www.acmicpc.net


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

๐ŸŽจ Go

// https://www.acmicpc.net/problem/10799
package main

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

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

	var input string
	fmt.Fscanln(reader, &input)
	inputs := strings.Split(input, "")
	fmt.Fprintln(writer, getBarCount(inputs))
}

func getBarCount(inputs []string) int {
	var stack []string
	var prev string
	var barCount int
	for i := 0; i < len(inputs); i++ {
		cur := inputs[i]
		if cur == "(" {
			stack = append(stack, cur)
		} else if cur == ")" {
			stack = stack[0 : len(stack)-1]
			if prev == "(" { // "(" ๋‹ค์Œ ")"๊ฐ€ ๋ฐ”๋กœ ๋“ค์–ด์˜ค๋ฉด ๋ ˆ์ด์ €
				barCount += len(stack) // ๋ ˆ์ด์ €์ธ ๊ฒฝ์šฐ ์Šคํƒ ์•ˆ์˜ ๊ด„ํ˜ธ ๊ฐฏ์ˆ˜๋งŒํผ ๋ง‰๋Œ€ ์นด์šดํŠธ.
			} else {
				barCount++ // ")" ๋‹ค์Œ ")"๊ฐ€ ๋“ค์–ด์˜จ ๊ฒฝ์šฐ ๋ง‰๋Œ€๊ธฐ ๋์˜ ๊ฐœ์ˆ˜ ํ•˜๋‚˜ ์นด์šดํŠธ.
			}
		}
		prev = cur
	}
	return barCount
}

๐ŸŽจ Python3

# https://www.acmicpc.net/problem/10799
import sys

def get_bar_count(inputs):
    stack = []
    prev = ""
    bar_count = 0
    for i in range(len(inputs)):
        cur = inputs[i]
        if cur == "(":
            stack.append(cur)
        elif cur == ")":
            stack.pop()
            if prev == "(":
                bar_count += len(stack)
            else:
                bar_count += 1
        prev = cur
    return bar_count

if __name__ == "__main__":
    inputs = list(sys.stdin.readline().rstrip())
    print(get_bar_count(inputs))
728x90
๋Œ“๊ธ€