취미로 음악을 하는 개발자

[Java] 프로그래머스 스택/큐, 쇠막대기 본문

공대인/Programmers

[Java] 프로그래머스 스택/큐, 쇠막대기

영월특별시 2019. 12. 3. 17:26
728x90
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
73
74
75
76
77
78
79
import java.util.Stack;
 
// 쇠막대기
public class IronRod {
    public static int solution(String arrangement) {
        arrangement = arrangement.replace("()""1");        // 레이저 처리
        int answer = 0;        // 쇠막대기 총 개수
        char curr;    // 배치
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < arrangement.length(); i++) {
            curr = arrangement.charAt(i);
            
            if (curr == '(')             // 쇠막대기 왼쪽
                stack.push(1);
 
            else if (curr == ')')     // 쇠막대기 오른쪽
                answer += stack.pop();
            
            else {                    // 레이저 처리
                answer += stack.size();
                // 통과 (8147.37ms, 351MB)
//                for (int j = 0; j < stack.size(); j++)
//                    stack.set(j, stack.get(j)+1);
            }
        }
        return answer;
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println(solution("()(((()())(())()))(())"));
    }
}
 
 
/* 테스트 케이스 1번 시간초과
import java.util.Stack;
// 쇠막대기
public class IronRod {
    public static int solution(String arrangement) {
        int answer = 0;
        char curr, next;
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < arrangement.length(); i++) {
            curr = arrangement.charAt(i);
            if (i < arrangement.length()-1)
                next = arrangement.charAt(i+1);
            else
                next = ')';
            
            
            if (curr == '(') {
                for (int j = 0; !stack.isEmpty() && j < stack.size(); j++)
                    stack.set(j, stack.get(j)+1);
                
                if (next == '(') 
                    stack.push(1);
                else  // next == ')'
                    answer += stack.size();
            }
            else {    // curr == ')'
                for (int j = 0; !stack.isEmpty() &&  j < stack.size(); j++)
                    stack.set(j, stack.get(j)-1);
                
                if(!stack.isEmpty() && stack.peek() == 0) {
                    stack.pop();
                    answer++;
                }
            }
        }
        return answer;
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println(solution("()(((()())(())()))(())"));
    }
}
*/
cs


https://programmers.co.kr/learn/courses/30/lessons/42585



Comments