leetcode 1208. 尽可能使字符串相等 2730. 找到最长的半重复子字符串
两道题差不多思路,放到一起
其中,字符串 s 和 t 只包含小写字母
法一:使用额外空间
class Solution {
public:
int equalSubstring(string s, string t, int maxCost) {
int size = s.size();
vector<int> cost(size);
for(int i = 0;i < size;i++) cost[i] = abs(s[i]-t[i]);
int left = 0,right = 0,resLenth = 0,nowCost = 0;
for(right = 0;right < size;right++){
nowCost += cost[right];
if(nowCost > maxCost){
resLenth = max(resLenth,right-left);
while(nowCost > maxCost) nowCost -= cost[left++];
}
}
return max(resLenth,right-left);
}
};
法二:不使用额外空间
class Solution {
public:
int equalSubstring(string s, string t, int maxCost) {
int size = s.size();
int left = 0,right = 0,resLenth = 0,nowCost = 0;
for(right = 0;right < size;++right){
nowCost += abs(s[right]-t[right]);
if(nowCost > maxCost){
resLenth = max(resLenth,right-left);
while(nowCost > maxCost){
nowCost -= abs(s[left]-t[left]);
++left;
}
}
}
return max(resLenth,right-left);
}
};
class Solution {
public:
int longestSemiRepetitiveSubstring(string s) {
int size = s.size();
if(size <= 2) return size;
int resLenth = 0,left = 0,right;
bool flag = false;
for(right = 1;right < size;++right){
if(s[right-1] == s[right]){
if(flag == false){
flag = true;continue;
}
resLenth = max(resLenth,right - left);
while(s[left] != s[left+1]) ++left;
++left;
}
}
return max(resLenth,right - left);
}
};