給定一個索引為 0 的二進制字串 s 和兩個整數 minJump 和 maxJump。一開始,您站在索引 0,它等于 '0'。如果滿足以下條件,您可以從索引 i 移動到索引 j:
i minJump <= j <= min(i maxJump, s.length - 1), and
s[j] == '0'.
Return true if you can reach index s.length - 1 in s, or false otherwise.
示例 1:
Input: s = "011010", minJump = 2, maxJump = 3
Output: true
Explanation:
In the first step, move from index 0 to index 3.
In the second step, move from index 3 to index 5.
示例 2:
Input: s = "01101110", minJump = 2, maxJump = 3
Output: false
約束:
2 <= s.length <= 105
s[i] is either '0' or '1'.
s[0] == '0'
1 <= minJump <= maxJump < s.length
我已經在 Dart 中完成了上述問題。但我沒有得到正確的輸出。由于我是 dart 新手,我請求你們所有人將這個問題的解決方案發送給我。我附上了我已經完成的代碼。
class Solution {
bool canReach(String s, int minJump, int maxJump) {
int N = s.length;
Vector<int> good(N);
good[0] = 1;
int M = 0;
for (int i=0; i<N; i ) {
if (s[i] == '0' & a[i]) {
int l = i minJump;
int r = min(N-1, i maxJump);
for (int j=max(l, M); j<=r; j ) {
good[j] = 1;
}
M = r 1;
if (M >= N) break;
}
}
return good.back() == 1 & s.back() == '0';
}
};
uj5u.com熱心網友回復:
我無法真正閱讀您的代碼或理解您的方法,因此我從頭開始嘗試使用帶有一些檔案的遞回設計。你還沒有發布那么多測驗用例,所以我只測驗了幾個:
bool canReach(String string, int minJump, int maxJump, [int startIndex = 0]) {
// We stands at the end of the string and stands on a `0` so home is reached
if (string.length == startIndex 1 && string[startIndex] == '0') {
return true;
}
// Go though each jump size
for (var jump = minJump; jump <= maxJump; jump ) {
final newPos = startIndex jump;
// If we have jumped over the length of the string, we just stop with
// further jumps.
if (newPos > string.length - 1) {
break;
}
// If we have jumped to a `0` we should check this as a candidate
if (string[newPos] == '0') {
// Recursive call from our new position
if (canReach(string, minJump, maxJump, newPos)) {
// If we reached home with our solution, we just stops here
return true;
}
}
}
// If we did not reached a `true` going though all jump size candidates,
// we mark our attempted solution as failed.
return false;
}
void main() {
print(canReach('011010', 2, 3)); // true
print(canReach('01101110', 2, 3)); // false
print(canReach('01101110', 2, 4)); // true
}
請告訴我是否有任何問題,或者您對此代碼的作業方式有任何疑問。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/387090.html
標籤:镖
下一篇:為什么我的切換按鈕有問題
