1208-尽可能使字符串相等

1208-尽可能使字符串相等

力扣1208

https://leetcode-cn.com/problems/get-equal-substrings-within-budget/

题目

第一直觉就是有一个dis数组记录了s[i]和t[i]的差距,也确实是这么做的,接下来一开始以为直接对dis排序即可,后来才发现是子字符串,所以是要连续的,因此这道题是一道滑动窗口题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public int equalSubstring(String s, String t, int maxCost) {
int res = 0;
int[] dis = new int[s.length()];
char[] sArr = s.toCharArray();
char[] tArr = t.toCharArray();

//统计s[i]和t[i]的差距
for (int i = 0; i < s.length(); i++) {
dis[i] = Math.abs(sArr[i] - tArr[i]);
}

//因为子字符串要求连续,所以滑动窗口
int l = 0, r = 0, len = 0;
while (r < s.length()){
if ((len + dis[r]) <= maxCost){
len += dis[r];
r++;
}else {
len -= dis[l];
l++;
}
res = Math.max(res, r - l);
}

return res;
}

python实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def equalSubstring(self, s: str, t: str, maxCost: int) -> int:
# 统计s[i]和t[i]的差距
dis = [abs(ord(s[i]) - ord(t[i])) for i in range(len(s))]

# 因为子字符串要求连续,所以滑动窗口
l, r, max_len, res = 0, 0, 0, 0
while r < len(s):
if max_len + dis[r] <= maxCost:
max_len += dis[r]
r += 1
else:
max_len -= dis[l]
l += 1
res = max(res, r - l)

return res

其他滑动窗口类型的题目可以点击这里

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×