计算雨水量: 取左右柱子最小值作为 h,左右索引距离为 w,横向计算雨水量 s 直至栈为空或当前右侧柱子小于栈顶柱子高度。
Java代码:
classSolution{publicinttrap(int[] height){if(height.length <=2)return0;Stack<Integer> stack =newStack<>();
stack.push(0);int sum =0;for(int i =1; i < height.length; i++){int top = stack.peek();if(height[i]< height[top]){
stack.push(i);}elseif(height[i]== height[top]){
stack.push(i);}else{while(!stack.isEmpty()&& height[i]> height[top]){int mid = stack.pop();if(!stack.isEmpty()){int left = stack.peek();int h =Math.min(height[left], height[i])- height[mid];int w = i - left -1;int s = h * w;
sum += s;
top = stack.peek();}}
stack.push(i);}}return sum;}}
classSolution{publicintlengthOfLongestSubstring(String s){if(s ==null|| s.length()==0)return0;char[] chars = s.toCharArray();Set<Character> set =newHashSet<>();int res =0;int left =0;for(int right =0; right < chars.length; right++){while(set.contains(chars[right])){
set.remove(chars[left]);
left++;}
set.add(chars[right]);
res =Math.max(res, right - left +1);}return res;}}