I am trying to cut several iron rods with a laser. For efficient operation, the iron rods are stacked from the bottom up, and the laser is fired vertically from above to cut the iron rods. The arrangement of the iron rod and laser satisfies the following conditions.
The figure below shows an example that satisfies the above conditions. The thick solid line drawn horizontally is the iron rod, the dot is the position of the laser, and the dotted arrow drawn vertically is the direction of the laser.
The arrangement of the laser and the iron bar can be expressed in order from left to right using parentheses as follows.
The parenthetical representation of the above example is given above the figure.
The iron rod is cut into several pieces by the laser. In the example above, the top two iron rods are cut into 3 and 2 pieces respectively, and the iron rods given in this way are cut into 17 pieces in total.
Write a program to find the total number of pieces of iron rod cut, given parentheses indicating the placement of the iron rod and the laser.
A parenthesis expression indicating the placement of the iron rod and laser on a single line is given without spaces. The maximum number of parentheses characters is 100,000.
()(((()())(())()))(())
(((()(()()))(())()))(()())
Prints an integer representing the total number of cut pieces per line.
17
24
function solution(s) {
let answer = 0,
count = 0;
for (let i in s) {
if (s[i] === '(') count++;
else {
count--;
if (s[i - 1] === '(') answer += count;
else answer += 1;
}
}
return answer;
}
function solution(s) {
let answer = 0,
stack = [];
for (let i = 0; i < s.length; i++) {
if (s[i] === '(') stack.push(s[i]);
else {
stack.pop();
if (s[i - 1] === '(') answer += stack.length;
else answer += 1;
}
}
return answer;
}