public Stack<Integer> stack; public Stack<Integer> minStack; /** initialize your data structure here. */ // 第一次见到这种类型的题目,有点懵逼 // 解题思路其实很简单,利用一个辅助栈来存放,保持栈顶元素始终为最小值 publicMinStack(){ stack = new Stack<>(); minStack = new Stack<>(); } publicvoidpush(int x){ stack.push(x); if(minStack.empty() || x <= minStack.peek()){ minStack.push(x); } } publicvoidpop(){ if(stack.pop().equals(minStack.peek())){ minStack.pop(); } } publicinttop(){ return stack.peek(); } publicintgetMin(){ return minStack.peek(); } }
/** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */
classSolution{ publicint[] maxSlidingWindow(int[] nums, int k) { // 求解滑动窗口内的最大值 int n = nums.length; int[] res = newint[n - k + 1]; int max = nums[0];
for(int i = 0; i < n - k + 1; i ++ ){ max = nums[i]; for(int j = i + 1; j < i + k; j ++ ){ if(nums[j] > max) max =nums[j]; } res[i] = max; } return res; } }
Stack<Integer> stack = new Stack<Integer>(); String tmp = null;
for(int i = 0; i < s.length();){ if(s.charAt(i) == '['){ stack.push(i); } if(s.charAt(i) == ']'){ int j = stack.pop(); int m = j; int time = 1; int times = 0; int count = 0;
while((s.charAt(m - 1) >= '0') && (s.charAt(m - 1) <= '9')){ times = (s.charAt(m - 1) - '0') * time + times; time = time * 10; m --; count ++; if(m < 1) break; }
String sub = s.substring(j + 1, i); int length = sub.length(); tmp = String.join("", Collections.nCopies(times, sub)); s = String.join("",s.substring(0, j - count), tmp , s.substring(i + 1, s.length())); i = j + times * length - count - 1; } i ++; } return s; } }