单调栈
当一个柱子的高度高过栈顶柱子时,表示栈顶柱子的右边界就是当前柱子;而栈顶元素的前一个柱子就是左边界。
int trap(vector<int>& height) {
if(height.empty()) return 0;
int res = 0;
int size = height.size();
stack<int> stk;
for(int cur = 0; cur<size;++cur){
while(!stk.empty() && height[stk.top()]<height[cur]){
int top = stk.top();
stk.pop();
if(stk.empty()) break;
int length = cur-stk.top()-1;
int high = min(height[stk.top()],height[cur])-height[top];
res += length*high;
}
stk.push(cur);
}
return res;
}