1 / 9

String Checker II

String Checker II. Sit-in lab 4. Problem Description. Given a number of strings containing only “a”, “b”, “c”, “d” Check each string that it follows the pattern a n b m c m d n where m, n >= 1 Use only stack OR queue. Solution. Look at pattern: a n b m c m d n Notice that it is LIFO

kaleb
Download Presentation

String Checker II

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. String Checker II Sit-in lab 4

  2. Problem Description • Given a number of strings containing only “a”, “b”, “c”, “d” • Check each string that it follows the pattern anbmcmdn where m, n >= 1 • Use only stack OR queue

  3. Solution • Look at pattern: anbmcmdn • Notice that it is LIFO • So we use a Stack! • Many ways of solving with a stack… here we show one way

  4. Solution • Process one character from the input String at a time. • For example: • for(int j = 0; j < s.length(); j++){strCheck.nextChar(s.charAt(j));}

  5. Solution • If character is “a” • We push to stack if • the stack is empty, or • the top of the stack is “a” • Else is not valid string • If character is “b” • Remember that we have a “b” (set a boolean flag) • We push to stack if • the stack is NOT empty, and • the top of the stack is “a” or “b” • Else is not valid string We need to check this so that things like “bc” will be caught

  6. Solution • If character is “c” • We pop from the stack if • the stack is NOT empty, and • the top of the stack is “b” • Else is not valid string • If character is “d” • We pop from the stack if • the stack is NOT empty, and • the top of the stack is “a”, and • there was a “b” read in (special check for things like “ad”) • Else is not valid string

  7. Solution • Finally, before concluding is valid string, check that stack is empty • We need this to catch things like “aaaaaabbccd” (there will be many “a” left behind in the stack)

  8. End

  9. String Checker I

More Related