[LeetCode] 717. 1-bit and 2-bit Characters

原题链接: https://leetcode.com/problems/1-bit-and-2-bit-characters/

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.

有两种字符,第一种字符可以被0代替,第二种字符可以被10或者11代替。
现在给出一个由字符0结尾的数组,数组中的全部元素都是0或者1。
问最后的0是否能够单独表示一个字符?

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.

2. 解题思路

这个题我是通过找规律做出来的。
如果数组的长度为1,由于最后一个数必须是0,因此必定为true。

如果数组的长度大于等于2,那么又可以分为两种情况:

  1. 数组以 00 结尾的,必定返回true
  2. 数组以 10 结尾的,需要进一步判断。

当数组长度大于等于2并且以10结尾时,我发现了这样一个规律:

从倒数第二个1开始向左数,直到出现0为止。连续的1的个数的奇偶可以帮助我们判断。
比如001010011110,从倒数第二个1向左数,直到遇到0为止,一共有1111四个连续的1。这四个连续的1中,第一个1和前面的0是不可能连起来代表1个字符的,所以只能在11110内部解决。
于是问题就变成了有n个连续的1,加上一个0的序列,最后一个0能否单独代表一个字符。当n为偶数时,0可以单独代表1个字符;当n为奇数时,0不能单独代表1个字符。

实现代码

class Solution {
    public boolean isOneBitCharacter(int[] bits) {
        int length = bits.length;
        if(length ==0) {
        	return false;
        }
        //由于最后一个数必定为0,因此length ==1必然为true
        if(length ==1 ) {
        		return true;
        }
        
        //length >= 2时
        //如果倒数第二个数也是0,必然为true
        if(bits[length -2] == 0) {
    		return true;
    	}
        //计算1的个数
    	int Count = 0;
        for(int i = length-2 ; i>=0 ; i--) {
        	if(bits[i] == 0) {  break;	}
        	else  {  Count++;  }
        }
        
        if(Count % 2 == 0) {  return true;  }
        else {   return false;  }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值