字母交换
这个是字节跳动的笔试题,感觉难度挺大的,用的是动态规划来解的。首先题目说只有小写字母,所以字符的类型的只有26种,为了简化问题我们只要一种一种字符讨论即可。对于每一个字符,只需要记下他的位置
p
o
s
[
c
]
pos[c]
pos[c],就是把这些位置转换成连续的最少转换次数,这就可以dp了。设
d
p
[
i
]
[
j
]
dp[i][j]
dp[i][j]表示把
i
i
i到
j
j
j这一段合在一起最少需要的次数,根据不等式
∣
x
−
a
∣
+
∣
x
−
b
∣
<
=
b
−
a
(
b
>
a
)
|x-a|+|x-b|<=b-a(b>a)
∣x−a∣+∣x−b∣<=b−a(b>a), 可以推导出其状态转移方程为:
d
p
[
i
]
[
j
]
=
d
p
[
i
+
1
]
[
j
−
1
]
+
p
o
s
[
j
]
−
p
o
s
[
i
]
−
(
j
−
1
−
i
)
+
1
dp[i][j]=dp[i+1][j-1]+pos[j]-pos[i]-(j-1-i)+1
dp[i][j]=dp[i+1][j−1]+pos[j]−pos[i]−(j−1−i)+1枚举的时候是先枚举小区间然后再枚举大区间。
AC代码
// 小学生一发的刷题之路
// 3月3号;
//
//
//
#pragma comment(linker, "/STACK:1024000000,1024000000") //解决爆栈,手动加栈;
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <queue>
#include <deque> //双向队列;
#include <cmath>
#include <set>
#include <stack>
#include <map>
#include <vector>
#include <cstdlib>
#include <iomanip>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
const double PI=acos(-1.0);
const double eps=1e-10;
const int maxn=1e3+5;
const int maxm=1e3+5;
const ll mod=1e9+7;
const int INF=1e9;
const ll llINF=1e18;
template<class T>
inline void read(T &ret){ //快速输入模版;
ret=0;
int f=1;
char c=getchar();
while(c<'0'||c>'9'){
if(c=='-') f=-1;
c=getchar();
}
while(c>='0'&&c<='9'){
ret=ret*10+c-'0';
c=getchar();
}
ret*=f;
}
template <class T>
inline void out(T ret){ //快速输出模版;
if(ret>9)
{
out(ret/10);
}
putchar(ret%10+'0');
}
string str;
int m,dp[maxn][maxn];
vector<int> pos[26];
int solve(int x,int m){ //把字母x合并在一起;
int n=pos[x].size();
//dp[i][j]表示把第i个到第j个字母合在一起需要消耗的次数;
//dp[i][j]=dp[i+1][j-1]+pos[j]-pos[i]+1;
int ans=1;
for(int i=0;i<n;i++) dp[i][i]=0;
for(int i=0;i<n-1;i++){
dp[i][i+1]=pos[x][i+1]-pos[x][i];
if(dp[i][i+1]<=m){
ans=2;
}
}
for(int len=2;len<n;len++)
for(int i=0;i<n-len;i++){
int j=i+len;
dp[i][j]=dp[i+1][j-1]+pos[x][j]-pos[x][i]-len+1;
if(dp[i][j]<=m){
ans=len+1;
}
}
return ans;
}
int main()
{
cin>>str;
scanf("%d",&m);
for(int i=0;i<str.length();i++){ //存储每个字母的位置;
pos[str[i]-'a'].push_back(i);
}
int ans=0;
for(int i=0;i<26;i++)
if(pos[i].size()){
ans=max(ans,solve(i,m));
}
printf("%d\n",ans);
return 0;
}
新的开始,每天都要快乐哈!