首页 > 其他 > 详细

717. 1-bit and 2-bit Characters

时间:2020-05-04 11:52:12      阅读:33      评论:0      收藏:0      [点我收藏+]

问题:

解码问题,给出一串0,1数列,

遇到1,则由10或11解码为一个字符。

否则遇到0,则单独0解码为一个字符。求解码到最后一个字符是否由0解码而来。

(给出数列,总是以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.

  

解法1:

按照题意遍历数列,由0~size,解码,解析到最后一个头字符刚好是最后一个字符到时候,则返回true

代码参考:

 1 class Solution {
 2 public:
 3     bool isOneBitCharacter(vector<int>& bits) {
 4         int n = bits.size();
 5         if(n<=0) return false;
 6         for(int i=0; i<n; i++){
 7             if(i==n-1) return true;
 8             if(bits[i]==1) i++;
 9         }
10         return false;
11     }
12 };

 

解法2:

从后往前遍历,寻找规律:

若倒数第二位为0,即 XXXX00,那么该数列最后一位一定是由0自己解码而来,返回true

后倒数第二位为1,即 XXXX10,那么有两种情况,一种同上X1解码&0自己解码,另一种为10解码而来。

那么再看前面到位数,

XXXX010 ,这种只有可能为 0 10 的解码而来

XXXX110 ,这种又有两种可能: X1 10 或者 11 0 的解码而来。

从以上可总结规律。

XXXX0111110(最后几位中,两个0中间有奇数个1),解码只可能为:(X)0 11 11 10

XXXX011110(最后几位中,两个0中间有偶数个1),解码只可能为:(X)0 11 11 0

因此,只需要从后考虑,两个零之间的1有奇数个还是偶数个。奇数个的话,则返回false,偶数个的话,则返回true

参考代码:

 1 class Solution {
 2 public:
 3     bool isOneBitCharacter(vector<int>& bits) {
 4         int cout1s = 0;
 5         for(int i=bits.size()-2; i>=0 && bits[i]!=0; i--){
 6             cout1s++;
 7         }
 8         return cout1s%2==0;
 9     }
10 };

 

717. 1-bit and 2-bit Characters

原文:https://www.cnblogs.com/habibah-chang/p/12825871.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!