717. One-bit and two-bits characters
記錄下,LeetCode Contest 56 題1,包括題目意思,和解題思路。
這個題目上來讀了好幾遍才理解它的意思,理解意思後,這個題目就比較簡單了。
不過為了提升演算法效率,進一步做了一些優化,優化後 beat 100% submission,重點看下優化思路吧。
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.
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.
題目的中文意思:
我們有兩個特殊的字元,第一個字元可以用一位來表達:0;第二個字元用兩位表達,要麼為10,要麼為11。
給出一個字串,判斷最後一位(位於最右側的位)是不是一定為0。
LeetCode一般給出的例子不是瞎舉的,而是非常有代表性的2個例子。
第一個例子 [1 0 0],顯然 第一個字元必須為1和0搭配為10(這是題目中第二個字元),所以第二個字元也就是最後一個字元必然為 0;
第一個例子 [1 1 1 0],顯然 第一個字元必須為1和1搭配為11,並且第二個字元必須為10,所以最後一個字元是10,而不是0 。
2 分析題目
設 bits為 n 位, 則如果判斷最後一位是0的話,即bits[n-1]=0,那麼
bits[n-2] 只可能為兩種情況:
- 如果bits.length=1,則只含有一個0字元,一定是;
- bits[n-2] = 0,即 …00,則這種結構表明一定是以0結尾;
- bits[n-2]=1 且 bits[n-3]=0,即 …010,這種結構一定不是最後一位為0;
- bits[n-2]=1 且 bits[n-3]=1,即 …110,這種情況不能確定最後一位一定是0 ,像題目中給出的例子 1110 便是其中一個最後一位不為0的代表,因此只有這種情況才需要遍歷
遍歷情況分析,如果遍歷時,i 能等於 n-1,表示最後一位為0,並且 return;等遍歷結束時,還沒返回,表明已經越過最後一位,返回 false 。
經過上述分析後,程式碼如下所示:
public class Solution {
public bool IsOneBitCharacter(int[] bits) {
int i=0;
if(bits.Length==1) //情況1
return true;
if(bits[bits.Length-2]==0) //情況2
return true;
if(bits.Length >2 && bits[bits.Length-2]==1 &&
bits[bits.Length-3]==0) //情況3
return false;
//情況4
while(i<bits.Length){
if(bits[i]==1){
i+=2;
}
else i++;
if(i==bits.Length-1)
return true;
}
return false;
}
}
演算法的時間複雜度為 O(n),空間複雜度為 O(1) 。
Beat 100% submission
請記住:每天一小步,日積月累一大步!
主要推送關於對演算法的思考以及應用的訊息。培養思維能力,注重過程,挖掘背後的原理,刨根問底。本著嚴謹和準確的態度,目標是撰寫實用和啟發性的文章,歡迎您的關注。
歡迎關注《演算法channel》公眾號