Re: [闲聊] 每日leetcode

楼主: oin1104 (是oin的说)   2024-05-28 08:56:55
You are given two strings s and t of the same length and an integer maxCost.
You want to change s to t. Changing the ith character of s to ith character of t
costs |s[i] - t[i]| (i.e., the absolute difference between the ASCII values of
the characters).
Return the maximum length of a substring of s that can be changed to be the same
as the corresponding substring of t with a cost less than or equal to maxCost.
If there is no substring from s that can be changed to its corresponding substri
ng from t, return 0.
题目:
给你两个字串 s跟t 还有maxCost
你可以更改每个字母的ascii值
但是更改总值不可以超过maxCost
问你最长的更改后相同子字串有多长
思路:
这种区间内求东西的
而且需要一直纪录更改区间内的值
所以用sliding window 就很方便
```cpp
class Solution {
public:
int equalSubstring(string s, string t, int maxCost)
{
int res = 0;
int len = s.size();
vector<int> paper(len , 0);
for(int i = 0 ; i < len ; i ++)
{
paper[i] = abs(s[i]-t[i]);
}
int l = 0;
int r = 0;
int cn = 0;
for(r = 0 ; r < len ; r ++)
{
cn += paper[r];
while(cn > maxCost)
{
cn -= paper[l];
l ++;
}
res = max(r-l+1, res);
}
return res;
}
};
```
然后我res = max(r-l+1, res);
感觉可以放在while循环里面
然后出循环了在检查值
早起刷题身体好
作者: SydLrio (狂岚嘴砲)   2024-05-28 08:57:00
芋圆宝早安
楼主: oin1104 (是oin的说)   2024-05-28 08:57:00
早安
作者: SydLrio (狂岚嘴砲)   2024-05-28 08:58:00
我爱你

Links booklink

Contact Us: admin [ a t ] ucptt.com