921. 使括号有效的最少添加
class Solution {
public int minAddToMakeValid(String s) {
int res=0;
int need=0;
for(int i=0;i<s.length();i++){
char ch=s.charAt(i);
if(ch=='('){
need++;
}
if(ch==')'){
need--;
if(need==-1){
need=0;
res++;
}
}
}
return res+need;
}
}
1541. 平衡括号字符串的最少插入次数
class Solution {
public int minInsertions(String s) {
int res=0;
int need=0;
for(int i=0;i<s.length();i++){
char ch=s.charAt(i);
if(ch=='('){
need+=2;
if(need%2==1){
res++;
need--;
}
}else{
need--;
if(need==-1){
res++;
need=1;
}
}
}
return res+need;
}
}
496. 下一个更大元素 I
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int[] res=new int[nums1.length];
int[] greater=new int[nums1.length];
for(int i=0;i<nums1.length;i++){
for(int j=0;j<nums2.length;j++){
if(nums1[i]==nums2[j]){
greater=nextGreaterElement(nums2);
res[i]=greater[j];
}
}
}
return res;
}
int[] nextGreaterElement(int[] nums){
int[] res=new int[nums.length];
Stack<Integer> s=new Stack<>();
for(int i=nums.length-1;i>=0;i--){
while(!s.isEmpty()&&s.peek()<=nums[i]){
s.pop();
}
res[i]=s.isEmpty()?-1:s.peek();
s.push(nums[i]);
}
return res;
}
}
739. 每日温度
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int[] res=new int[temperatures.length];
Stack<Integer> s=new Stack<>();
for(int i=temperatures.length-1;i>=0;i--){
while(!s.isEmpty()&&temperatures[s.peek()]<=temperatures[i]){
s.pop();
}
res[i]=s.isEmpty()?0:(s.peek()-i);
s.push(i);
}
return res;
}
}
503. 下一个更大元素 II
class Solution {
public int[] nextGreaterElements(int[] nums) {
int n=nums.length;
int[] res=new int[n];
Stack<Integer> s=new Stack<>();
for(int i=2*n-1;i>=0;i--){
while(!s.isEmpty()&&s.peek()<=nums[i%n]){
s.pop();
}
res[i%n]=s.isEmpty()?-1:s.peek();
s.push(nums[i%n]);
}
return res;
}
}