1. 程式人生 > >leetcode-717-1-bit and 2-bit Characters

leetcode-717-1-bit and 2-bit Characters

leet present color ever can 條件 XP sub 什麽

題目描述:

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.

要完成的函數:

bool isOneBitCharacter(vector<int>& bits)

說明:

1、給定一個vector,每個元素或者為1或者為0,最後一個元素必定為0,要對這個vector做編碼,元素0代表一種字符,10或者11代表另一種字符,要求判斷編碼之後最後一個字符是不是0代表的字符。

給個例子[1,0,0],編碼為,10代表的字符和0代表的字符。所以返回true,最後一個字符是0代表的字符。

再給個例子[1,1,1,0],編碼為,11代表的字符和10代表的字符。所以返回false,最後一個字符是10代表的字符。

2、理解了題意之後,由於最後一個元素必定為0,所以判斷一下倒數第二個元素是不是0,如果是0,那麽必定最後一個字符是0代表的字符,如果不是,我們再做判斷。

筆者覺得從前面開始數起,可能還是比較容易做的方式,所以我們構造如下代碼:

    bool isOneBitCharacter(vector<int>& bits) 
    {
        int s1=bits.size();
        if(bits[s1-2]==0)//判斷倒數第二個元素是否為0
            return true;
        int i=0;
        while(i<s1)
        {
            if(bits[i]==1)
                i+=2;
            else
            {
                if(i==s1-1)//如果i能夠走到s1-1這個點
                    return true;//那麽就要返回true
                i+=1;
            }      
        }
        return false;
    }

上述代碼思路十分直接,實測7ms,beats 51.31% of cpp submissions。

3、改進:

上述做法中比較浪費時間的就是else語句裏面的if語句,每次都要進行判斷,十分浪費時間,而實際上我們只需要讓 i 走到最後的時候停下來,然後再做一次判斷是不是在s1-1這個位置就好了。

這樣就不用每次都做條件判斷了。

代碼如下:

    bool isOneBitCharacter(vector<int>& bits) 
    {
        int s1=bits.size();
        if(bits[s1-2]==0)
            return true;
        int i=0;
        while(i<s1-1)//這裏改成s1-1
        {
            if(bits[i]==1)
                i+=2;
            else
                i+=1;     
        }
        if(i==s1-1)
            return true;
        else
            return false;
    }

分析一下為什麽上述代碼能夠成立。

如果最後一個字符是0代表的字符,那麽有三種情況,如下:

s1-3 s1-2 s1-1
0 0
1 0 0
1 1 0

最後一個字符是0代表的字符,倒數第二個字符是0代表的字符或者11和10代表的字符。

那麽上述改進的代碼最後都會進行最後一次循環,然後i=s1-1,退出循環。

如果最後一個字符不是0代表的字符,最後兩個元素是10,那麽上述代碼進行完最後一次循環,i=s1,退出循環。

所以我們最後再做一次判斷就可以了,判斷 i 的位置。

上述代碼實測6ms,beats 98.74% of cpp submissions。

leetcode-717-1-bit and 2-bit Characters