数据结构_数组

目录

*数组字符串1-bit or 2-bit

数组字符串单个字符问题

717.1-bit and 2-bit Characters

  • 我自己的想法:
    数组最后一个一定是个0,考虑数组倒数第二个元素。如果是为0,则返回true;如果是1,计算除最后一个元素的数组长度的奇偶
    如果是奇数则返回true
    这个想法漏洞百出

参考别人的解题思路:

  • We don't need to traverse the whole array, just check the last part of it.
  • if there is only one symbol in array the answer is always true (as last element is 0)
  • if there are two 0s at the end again the answer is true no matter what the rest symbols are( ...1100, ...1000,)
  • if there is 1 right before the last element(...10), the outcome depends on the count of sequential 1, i.e.
    a) if there is odd amount of 1(10, ...01110, etc) the answer is false as there is a single 1 without pair
    b) if it's even (110, ...011110, etc) the answer is true, as 0 at the end doesn't have anything to pair with
class Solution {
public:
    bool isOneBitCharacter(vector<int>& bits) {
        int len=bits.size();
        if(len==1)
            return true;
        int ones=0;
        for(int i=len-2;i>=0&&bits[i]!=0;i--){
            ones++;
        }
        if(ones%2>0) return false;
        return true;
    }
};

猜你喜欢

转载自www.cnblogs.com/GeekDanny/p/9789757.html