leetcode:225周赛:5662. 满足三条件之一需改变的最少字符数(双指针)
作者:互联网
题目:
分析:
排序,然后,双指针。
代码:
class Solution {
public:
int minn=1<<30;
int f(string s1,string s2)
{//s1严格小于s2
if(s1[s1.size()-1]<s2[0]) return 0;
//枚举修改:s1的后半段,s2的前半段。
//先特殊,s1中不能包含‘z’ s2中不能包含‘a’
int ans=0;
for(int i=0;i<s2.size();i++)
if(s2[i]=='a') {
ans++;
s2[i]='z';
}
else break;
for(int i=s1.size()-1;i>=0;i--)
if(s1[i]=='z') {
ans++;
s2[i]='a';
}
else break;
if(ans>=minn) return minn;
sort(s1.begin(),s1.end());
sort(s2.begin(),s2.end());
if(s1[s1.size()-1]<s2[0]) return ans;
int t2=0;//s2的下标
int t1=0;
for(;t1<s1.size();t1++)
{
if(s1[t1]>=s2[t2]) break;
}
int ans2=min((int)(s2.size()),(int)(s1.size()));
ans2=min(t2+(int)(s1.size())-t1,ans2);
//双指针
t2++;
while(1)
{
while(t2<s2.size()&&s2[t2-1]==s2[t2]) t2++;
if(t2>=s2.size()) break;
for(;t1<s1.size();t1++)
{
if(s1[t1]>=s2[t2]) break;
}
ans2=min(ans2,t2+(int)(s1.size())-t1);
t2++;
if(t2>=s2.size()) break;
}
return ans2+ans;
}
int minCharacters(string a, string b) {
sort(a.begin(),a.end());
sort(b.begin(),b.end());
//变成一样的:
map<char,int> m;
for(int i=0;i<a.size();i++) m[a[i]]++;
for(int i=0;i<b.size();i++) m[b[i]]++;
int maxx=0;
for(int i=0;i<26;i++) maxx=max(maxx,m['a'+i]);
minn=(int)(a.size())+(int)(b.size())-maxx;
return min(min(f(a,b),f(b,a)),minn);
}
};
标签:周赛,int,s2,s1,t2,5662,225,ans2,size 来源: https://blog.csdn.net/weixin_42721412/article/details/113094949