dev/algorithm
BOJ / 4949๋ฒ / ๊ท ํ์กํ ์ธ์ [Go][Python3]
crscnt
2020. 11. 7. 21:00
๐ฉ๐ป๐ป ๋ฌธ์
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