Regex Oneliners


  • 1

    Current shortest from below:

    def is_one_bit_character(bits)
      bits.join !~ /^(0|1.)*1.$/
    end
    

    Solution 1

    Just decode the text and check the last character.

    Ruby:

    def is_one_bit_character(bits)
      bits.join.scan(/0|1./).last == '0'
    end
    

    Python:

    def isOneBitCharacter(self, bits):
        return re.findall('0|1.', ''.join(map(str, bits)))[-1] == '0'
    

    Solution 2

    Like solution 1, but with a slightly shorter/trickier regex:

    def is_one_bit_character(bits)
      bits.join.scan(/1?./).last == '0'
    end
    

    Solution 3

    Using other people's "even number of ones before the final zero" rule.

    def is_one_bit_character(bits)
      bits.join.match?(/(^|0)(11)*0$/)
    end
    

    The "not odd" version is a bit shorter, since !~ returns a boolean, unlike =~ would.

    def is_one_bit_character(bits)
      bits.join !~ /(^|0)(11)*10$/
    end
    

    A neat non-regex one:

    def is_one_bit_character(bits)
      bits.reverse.rotate.index(0).even?
    end
    

    The rotate achieves two things: It removes the zero that I need to skip, and it places it at the other end to ensure that index finds a zero.

    Solution 4

    Similar to solution 1, but using the regex to check the last character. Inspired by @chris-rocco7's solution.

    Ruby:

    def is_one_bit_character(bits)
      bits.join.match?(/^(0|1.)*0$/)
    end
    

    The "not not" version is shorter again:

    def is_one_bit_character(bits)
      bits.join !~ /^(0|1.)*1.$/
    end
    

    Python:

    def isOneBitCharacter(self, bits):
        return bool(re.match('(0|1.)*0$', ''.join(map(str, bits))))
    

    Java:

    public boolean isOneBitCharacter(int[] bits) {
        return Arrays.stream(bits).mapToObj(String::valueOf).collect(Collectors.joining()).matches("(0|1.)*0");
    }
    

    The matching part is nicer in Java, here it helps that Java means full match by default, but omg is turning the int[] to a String complicated. And that's already the nicest one I found here. Though I guess I could do a less efficient non-oneliner one:

    public boolean isOneBitCharacter(int[] bits) {
        String s = "";
        for (int bit : bits)
            s += bit;
        return s.matches("(0|1.)*0");
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.