본문 바로가기

Algorithm/Greedy

(C++) - LeetCode (easy) 717. 1-bit and 2-bit Characters

반응형

https://leetcode.com/problems/1-bit-and-2-bit-characters/description/

 

1-bit and 2-bit Characters - LeetCode

Can you solve this real interview question? 1-bit and 2-bit Characters - 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). Given a binary array bits that

leetcode.com

규칙을 찾아 구현하는 문제였습니다.

📕 풀이방법

📔 풀이과정

2개의 bit먼저 최대한 사용했을 때 마지막 1개의 bit가 남는지를 확인하면 됩니다.bits의 size만큼 for loop를 수행합니다.1. bits[i]가 1이라면 10 또는 11로 표현 가능하므로 2칸을 건너뛰게 됩니다.2. i == bits의 끝이라면 0으로 끝나는 bits이므로 true를 반환하면 됩니다.


📕 Code

📔 C++

class Solution {
public:
    bool isOneBitCharacter(vector<int>& bits) {
        for(int i = 0; i < bits.size(); i++) {
            if(i == bits.size() - 1) return true;
            if(bits[i]) i++;
        }
        return false;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.