[LeetCode]1-bit and 2-bit Characters 1位和2位字符

简介: 链接:https://leetcode.com/problems/1-bit-and-2-bit-characters/description/难度:Easy题目:717.

链接https://leetcode.com/problems/1-bit-and-2-bit-characters/description/
难度:Easy
题目:717. 1-bit and 2-bit We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11).

Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero.

Example 1:

Input: 
bits = [1, 0, 0]
Output: True
Explanation: 
The only way to decode it is two-bit character and one-bit character. So the last character is one-bit character.

Example 2:

Input: 
bits = [1, 1, 1, 0]
Output: False
Explanation: 
The only way to decode it is two-bit character and two-bit character. So the last character is NOT one-bit character.

Note:

  • 1 <= len(bits) <= 1000.
  • bits[i] is always 0 or 1.

翻译:给定两种字符,一种用1位的0表示,另一种用2位10或者11表示。现在给出一个由很多位字符表示的字符串,判断最后一位是不是1位字符。

思路:从头到尾遍历,如果该位数字为1,则向后前进两位,否则前进1位,循环的条件是i < n-1,即留出最后一位,所以当循环退出后,当i正好停留在n-1上,说明最后一位是单独分割开的。

参考代码
Java

class Solution {
    public boolean isOneBitCharacter(int[] bits) {
        int n = bits.length;
        int i = 0;
        while(i<n-1){
            if(bits[i]==0)
                i ++;
            else
                i += 2;
        }
        return i == n-1;
    }
}
目录
相关文章
|
3月前
|
存储 算法 程序员
【Leetcode 程序员面试金典 01.01】判定字符是否唯一 —— 位运算|哈希表
可以使用哈希表或位运算来解决此问题:由题可知s[i]仅包含小写字母,int[26]即能表示字符的出现次数;
|
3月前
|
算法
LeetCode算法题---无重复字符的最长子串、寻找两个正序数组的中位数(三)
LeetCode算法题---无重复字符的最长子串、寻找两个正序数组的中位数(三)
39 0
|
1月前
|
网络协议
《 LeetCode 热题 HOT 100》——无重复字符的最长子串
《 LeetCode 热题 HOT 100》——无重复字符的最长子串
|
2月前
|
存储 算法 Go
LeetCode 第三题: 无重复字符的最长子串
  给定一个字符串,请你找出其中不含有重复字符的最长子串的长度。
|
3月前
【Leetcode 2707】字符串中的额外字符 —— 动态规划
1. 状态定义:把`s[i−1]`当做是额外字符,`d[i] = d[i−1] + 1` 2. 状态转移方程:遍历所有的`j(j∈[0,i−1])`,如果子字符串`s[j...i−1]`存在于`dictionary`中,那么`d[i] = min d[j] 3. 初始状态`d[0] = 0`,最终答案为`d[n]`
|
3月前
leetcode:3. 无重复字符的最长子串
leetcode:3. 无重复字符的最长子串
16 0
|
3月前
|
算法
leetcode:387. 字符串中的第一个唯一字符
leetcode:387. 字符串中的第一个唯一字符
13 0
|
3月前
|
存储 索引
力扣1445 连续字符
力扣1445 连续字符
21 0
|
3月前
leetcode-777:在LR字符串中交换相邻字符
leetcode-777:在LR字符串中交换相邻字符
23 0

热门文章

最新文章