zoukankan      html  css  js  c++  java
  • 717. 1-bit and 2-bit Characters

    问题:

    解码问题,给出一串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 };
  • 相关阅读:
    Java多线程详解
    自动化构建工具Maven
    解决 安装cocoapods失败,提示 requires Ruby version >=2.2.2
    安装Cocoapods时候ERROR: While executing gem ... (Errno::EPERM)
    iOS可执行文件瘦身方法
    ios webview自适应实际内容高度4种方法
    iOS8 tableview separatorInset cell分割线左对齐,ios7的方法失效了
    Reveal1.5破解,iOS_UI调试利器Reveal最新版本破解方法
    Xcode安装插件,错误选择了Skip Bundles,重新出现Load Bundles方法
    10分钟搞定支付宝支付 的 各种填坑
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/12825871.html
Copyright © 2011-2022 走看看