C#LeetCode刷题之#717-1比特与2比特字符( 1-bit and 2-bit Characters)

C#LeetCode刷题之#717-1比特与2比特字符( 1-bit and 2-bit Characters)

问题

有两种特殊字符。第一种字符可以用一比特0来表示。第二种字符可以用两比特(10 或 11)来表示。

现给一个由若干比特组成的字符串。问最后一个字符是否必定为一个一比特字符。给定的字符串总是由0结束。

输入: bits = [1, 0, 0]

输出: True

解释: 唯一的编码方式是一个两比特字符和一个一比特字符。所以最后一个字符是一比特字符。

输入: bits = [1, 1, 1, 0]

输出: False

解释: 唯一的编码方式是两比特字符和两比特字符。所以最后一个字符不是一比特字符。

注意:

1 <= len(bits) <= 1000.
bits[i] 总是0 或 1.

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.

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.

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.

示例

public class Program {

    public static void Main(string[] args) {
        int[] nums = null;

        nums = new int[] { 1, 1, 1, 0 };
        var res = IsOneBitCharacter(nums);
        Console.WriteLine(res);

        Console.ReadKey();
    }

    private static bool IsOneBitCharacter(int[] bits) {
        //1总是要和后面的1个数字编码,即+2,0不用编码,+1往后继续即可
        //这道题做不出来主动面壁思过吧
        int i = 0;
        while(i < bits.Length - 1) {
            i = bits[i] == 0 ? ++i : i + 2;
        }
        return i == bits.Length - 1;
    }

}

以上给出1种算法实现,以下是这个案例的输出结果:

False

分析:

显而易见,以上算法的时间复杂度为: O(n)

本文由 .Net中文网 原创发布,欢迎大家踊跃转载。

转载请注明本文地址:https://www.byteflying.com/archives/3740

发表评论

登录后才能评论