717. 1-bit and 2-bit Characters
leetcode easy
#array#bit-manipulation#csharp#easy#leetcode#string
Task
У нас есть два специальных символа: первый символ может быть представлен одним битом 0. Второй символ может быть представлен двумя битами (10 или 11). Если задан двоичный массив bits, который заканчивается 0, верните true, если последний символ должен быть однобитным.
Пример:
Input: bits = [1,0,0]
Output: true
C# solution
matched/originalpublic class Solution {
public bool IsOneBitCharacter(int[] bits) {
int i = 0;
while (i < bits.Length - 1) {
i += bits[i] + 1;
}
return i == bits.Length - 1;
}
}C++ solution
auto-draft, review before submit#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
public bool IsOneBitCharacter(vector<int>& bits) {
int i = 0;
while (i < bits.size() - 1) {
i += bits[i] + 1;
}
return i == bits.size() - 1;
}
}Java solution
auto-draft, review before submitimport java.util.*;
import java.math.*;
// Auto-generated Java draft from the C# solution. Review API differences before LeetCode submit.
public class Solution {
public boolean IsOneBitCharacter(int[] bits) {
int i = 0;
while (i < bits.length - 1) {
i += bits[i] + 1;
}
return i == bits.length - 1;
}
}JavaScript solution
matched/originalvar isOneBitCharacter = function(bits) {
let i = 0;
while (i < bits.length - 1) {
i += bits[i] + 1;
}
return i === bits.length - 1;
};Python solution
matched/originaldef isOneBitCharacter(bits):
i = 0
while i < len(bits) - 1:
i += bits[i] + 1
return i == len(bits) - 1Go solution
matched/originalpackage main
func isOneBitCharacter(bits []int) bool {
i := 0
for i < len(bits) - 1 {
i += bits[i] + 1
}
return i == len(bits) - 1
}Explanation
Algorithm
Инициализируйте индекс для итерации по массиву.
Пройдите по массиву, увеличивая индекс на 1, если текущий бит равен 0, и на 2, если текущий бит равен 1.
Проверьте, достиг ли индекс последнего элемента массива, и верните результат.
😎