-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdefault.rb
73 lines (58 loc) · 1.03 KB
/
default.rb
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#
# @lc app=leetcode.cn id=1963 lang=ruby
# @lcpr version=30204
#
# [1963] 使字符串平衡的最小交换次数
#
# @lcpr-template-start
# @lcpr-template-end
# @lc code=start
# @param {String} s
# @return {Integer}
def min_swaps(s)
count = 0
left = 0
right = s.length - 1
left_stack = []
right_stack = []
while left < right
if s[left] == '['
left_stack.push(s[left])
left += 1
next
end
if s[left] == ']' && left_stack.last == '['
left_stack.pop
left += 1
next
end
if s[right] == ']'
right_stack.push(s[right])
right -= 1
next
end
if s[right] == '[' && right_stack.last == ']'
right_stack.pop
right -= 1
next
end
s[left], s[right] = s[right], s[left]
count += 1
end
count
end
# @lc code=end
#
# @lcpr case=start
# "][]["\n
# @lcpr case=end
# @lcpr case=start
# "]]][[["\n
# @lcpr case=end
# @lcpr case=start
# "[]"\n
# @lcpr case=end
# @lcpr case=start
# "[]][[[]]]]][[[[]]]]]]]]][[[[[[[["\n
# @lcpr case=end
#