# leetcode161周赛题解-贪心、栈、数学

1、交换字符使得字符串相同

输入：s1 = "xx", s2 = "yy"



输入：s1 = "xy", s2 = "yx"



输入：s1 = "xx", s2 = "xy"



1 <= s1.length, s2.length <= 1000
s1, s2 只包含 'x' 或 'y'。


java
class Solution {

public int minimumSwap(String s1, String s2)
{
if(s1.length()!=s2.length())
return -1;
int cnt1=0,cnt2=0;
for(int i=0;i<s1.length();i++)
{
if(s1.charAt(i)!=s2.charAt(i))
{
if(s1.charAt(i)=='x')
cnt1++;
else
cnt2++;
}
}
if((cnt1+cnt2)%2==1)
return -1;
cnt1=(cnt1%2==0)?cnt1/2:cnt1/2+1;
cnt2=(cnt2%2==0)?cnt2/2:cnt2/2+1;
return cnt1+cnt2;

}

}


2、统计「优美子数组」

输入：nums = [1,1,2,1,1], k = 3



输入：nums = [2,4,6], k = 1



输入：nums = [2,2,2,1,2,2,1,2,2,2], k = 2



1 <= nums.length <= 50000
1 <= nums[i] <= 10^5
1 <= k <= nums.length


class Solution {

public int numberOfSubarrays(int[] nums, int k)
{
int cnt=0;
for(int i=0;i<nums.length;i++)
if(nums[i]%2==1)
{
cnt++;
}
if(cnt<k)
return 0;
int[] arr=new int[nums.length];
int t=0;
for(int i=0;i<arr.length;i++)
{
if(nums[i]%2==0)
t++;
else
{
arr[i]=t;
t=0;
}
}
List<Integer> list1=new ArrayList<Integer>();
List<Integer> list2=new ArrayList<Integer>();
for(int i=0;i<arr.length;i++)
{
if(nums[i]%2==1)
{
if(list1.isEmpty())
else
{
}
}
}
int ans=0;
for(int i=0;i<list1.size();i++)
{
if(i+k-1<list2.size())
{
ans+=(list1.get(i)+1)*(list2.get(i+k-1)+1);
}
}
return ans;
}

}


3、移除无效的括号

空字符串或只包含小写字母的字符串



输入：s = "lee(t(c)o)de)"



输入：s = "a)b(c)d"



输入：s = "))(("



输入：s = "(a(b(c)d)"



1 <= s.length <= 10^5
s[i] 可能是 '('、')' 或英文小写字母


class Solution {

public String minRemoveToMakeValid(String s)
{
Stack<Integer> st=new Stack<Integer>();
char[] chs = s.toCharArray();
for(int i=0;i<chs.length;i++)
{
if(chs[i]==')')
{
if(st.isEmpty())
chs[i]=' ';
else
st.pop();
}
else if(chs[i]=='(')
st.push(i);
}
while(!st.isEmpty())
chs[st.pop()]=' ';
s=new String(chs);
s=s.replaceAll(" ", "");
return s;
}

}


4、 检查「好数组」

输入：nums = [12,5,7,23]

5*3 + 7*(-2) = 1


输入：nums = [29,6,10]

29*1 + 6*(-3) + 10*(-1) = 1


输入：nums = [3,6]



1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9


class Solution {

public boolean isGoodArray(int[] nums)
{
int dd=nums[0];
for(int i=0;i<nums.length;i++)
dd=gcd(dd,nums[i]);
return dd==1;
}

private int gcd(int m, int n)
{
return m%n==0?n:gcd(n, m%n);
}

}
`
04-23 1953
11-03 233

11-05 358
11-03 2522
03-13 153
07-21 37
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客