Regular expression for strings with an even number of zeroes and ones

后端 未结 4 1897
逝去的感伤
逝去的感伤 2021-01-12 08:06

What is a regular expression for strings of 0 and 1 with an even number of zeros and an even number of ones?

I have something like (1*01*01*)*(0*10*10*)*

相关标签:
4条回答
  • 2021-01-12 08:17

    A counterexample for your given regular expression is 01010101.

    You may find that writing a regular expression for this particular problem is not going to be possible (unless you use some non-regular extensions to the usual regular expression language).

    As mentioned by Jim Lewis below, this should indeed be a solvable problem.

    0 讨论(0)
  • 2021-01-12 08:21

    Well, this is probably homework, but what the heck:

    ^(00|11|(01|10)(00|11)*(01|10))*$
    

    Edit: simplified!

    0 讨论(0)
  • 2021-01-12 08:29

    1100 is in the language, but doesn't match your expression. 10101 is not in the language, but your expression matches it.

    I'd suggest starting by drawing a DFA. There's a pretty obvious 4-state machine that recognizes this language. (Is it possible to do better?) The empty string is in the language, so the start state is an accepting state. Are there other accepting states? For a non-accepting state S, is there a prefix that takes you from start->S? Is there a way to loop from S back to S without hitting an accepting state? Is there suffix that takes you from S back to an accepting state?

    0 讨论(0)
  • 2021-01-12 08:38
    @tmp = $str =~ /0/g;
    
    print scalar @tmp % 2 == 0 ? 'even' : 'odd';
    
    0 讨论(0)
提交回复
热议问题