NumberOfDiscIntersections

problem

solution

經典stack 教材

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// you can use includes, for example:
// #include <algorithm>

// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;

#include<stack>
int solution(string &S) {
// write your code in C++14 (g++ 6.2.0)
stack<char> sta;
for(char c:S){
if(c=='(' || c=='[' || c=='{') sta.push(c);
else{
if(sta.empty()) return false;
else if(sta.top() == '(' && c==')') sta.pop();
else if(sta.top() == '[' && c==']') sta.pop();
else if(sta.top() == '{' && c=='}') sta.pop();
else return false;
}
}
return sta.empty();
}

analysis

  • time complexity O(n)
  • space complexity O(n)