- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathequal-substring.ts
57 lines (45 loc) · 1.28 KB
/
equal-substring.ts
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/**
* @description leetcode1208 尽可能使字符串相等
* @author tangc1
* @date 2022-07-31 20:35:03
*/
/**
* @param {string} s
* @param {string} t
* @param {number} maxCost
* @return {number}
*/
exportfunctionequalSubstring1(s: string,t: string,maxCost: number): number{
if(s==''||t=='')return0
constlen=s.length
letleft=0,right=0;
letcost=0,result=0;
// @ts-ignore
constgetCost=i=>Math.abs(s[i].charCodeAt()-t[i].charCodeAt())
while(right<len){
cost+=getCost(right++)
while(left<=right&&cost>maxCost){
cost-=getCost(left++)
}
result=Math.max(result,right-left)
}
returnresult
}
exportfunctionequalSubstring2(s: string,t: string,maxCost: number): number{
if(s==''||t=='')return0
constlen=s.length
constdiff=newArray(len).fill(0)
for(leti=0;i<len;i++){
// @ts-ignore
diff[i]=Math.abs(s[i].charCodeAt()-t[i].charCodeAt())
}
letleft=0,right=0,result=0,cost=0;
while(right<len){
cost+=diff[right++]
while(cost>maxCost){
cost-=diff[left++]
}
result=Math.max(result,right-left)
}
returnresult
}