1578. Minimum Time to Make Rope Colorful - Medium
前往題目
想法
- 雙指針
思路
- 雙指針,循環整個字串
- 每次循環檢查字符是否相同
- 相同時紀錄所需時間,移動左指針
- 不同時只移動指針
Code
class Solution {
public int minCost(String colors, int[] neededTime) {
int l = 0, r = 1;
int res = 0;
// 走過整個字串
while (r < colors.length()) {
char leftCh = colors.charAt(l);
char rightCh = colors.charAt(r);
// Consecutive identical chars
if (leftCh == rightCh) {
// 所需時間左邊較少
if (neededTime[l] < neededTime[r]) {
res += neededTime[l];
l = r; // 移動左指針到右指針位置
} else {
res += neededTime[r];
}
} else { // 不同字符
l = r;
}
++r;
}
return res;
}
}
1578. Minimum Time to Make Rope Colorful - Medium
https://f88083.github.io/2024/07/10/1578-Minimum-Time-to-Make-Rope-Colorful/