균형잡힌_세상_4949번

[Python, Go] 백준 4949번 풀이

균형잡힌 세상

  • 괄호문제 의 연장이다.

  • 소괄호뿐만 아니라 대괄호까지 포함해 문장에서 괄호가 올바르게 되어져있는지 확인해야한다.

  • 괄호안에 있는 괄호의 짝도 맞아야 yes를 출력할 수 있다. 예를들어 ( [ ) ] 와 같은 경우 하나의 괄호 안에 올바른 짝의 괄호가 들어가지 못했으므로 no 를 출력해야 한다.

  • 정규표현식을 사용해 따라가야될 괄호들을 뺀 문자들은 pass 시켜주는 방법을 사용했다.

  • 이외에는 괄호문제와같이 스텍에 ( 와 [ 를 담아서 사용했다.

    • 단 ) 와 ] 를 만났을 때, 스텍의 마지막 요소가 짝이되는 괄호인지를 판별해줘야 한다.
  • Python 풀이
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def vps(line):
stack = []
if line[0] == ")" or line[0] == "]":
# print("1")
return "no"
else: pass
for s in line:
if bool(com.match(s)) == True:
pass
elif s == " " or s == ".":
pass
elif s == "(" or s == "[":
stack.append(s)
# print(stack)
elif s == ")" and stack != []:
if stack[-1] == "(":
stack.pop()
else:
# print("2")
return "no"
elif s == "]" and stack != []:
if stack[-1] == "[":
stack.pop()
else:
# print("3")
return "no"
else:
# print("4")
return "no"
if stack == []:
return "yes"
else:
# print("5")
return "no"
  • Go 풀이
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
func vps(x string) string {
var stack []string

// fmt.Println(string(x[0]))
// return x
if string(x[0]) == ")" || string(x[0]) == "]" {
return "no"
}
for _, ch := range x {
s := string(ch)
match, _ := regexp.MatchString("[a-zA-Z]", s)
if match == true {
} else if s == " " || s == "." {
} else if s == "(" || s == "[" {
stack = append(stack, s)
} else if s == ")" && stack != nil {
if stack[len(stack)-1] == "(" {
if len(stack) == 1 {
stack = nil
} else {
stack = stack[:len(stack)-1]
}
} else {
return "no"
}
} else if s == "]" && stack != nil {
if stack[len(stack)-1] == "[" {
if len(stack) == 1 {
stack = nil
} else {
stack = stack[:len(stack)-1]
}
} else {
return "no"
}
} else {
return "no"
}
}
if stack == nil {
return "yes"
} else {
return "no"
}
}
  • Go로 풀이할때, 조건이 많을때는 switch가 더 좋기때문에 switch를 사용했다면 더 좋았을것같다.

Full Code

Full Code - Python

Full Code - Go

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×