tags:

views:

121

answers:

2

Given a string of characters as input, without using regular expression or pattern matching, how to get the output, if the characters matches aaa should output 1 and if the characters matches aBa should output 2. (Note: Should not re-process characters so as to output both “1” and “2” when processing the same input)

So for example:

given 'aaBaBaaaBaaa' it should output 211

given 'aaaBaBaaaaBBaBaBa' it should output 1212

Thanks in advance.

PS: I have posted the same problem for a solution in Ruby at http://stackoverflow.com/questions/2022436/ruby-program-problem which might give some insight about the implementation.

A: 

Loop through the string one character at a time from the beginning until there are only 3 left. During each loop, examine the first 3 characters. If they match aaa, append 1 to the output and remove the first 3 characters. Or, If they aBa, append 2 to the output and remove the first 3 characters. Otherwise, just remove the first character before looping again.

If you want flexible patterns, you'll have to loop through your list of patterns during each examination, and remove the correct number of characters if a pattern is hit. Also the loop should keep checking until the number of characters left is less than the smallest pattern.

If you already have a solution in Ruby, does that mean you're just looking for code? Your question is tagged homework, so generally copy/paste code answers shouldn't be given.

Ross
"I have this Ruby solution, and I'm trying to convert it to Java but I'm having trouble because [insert details here]" is a good question. "How do you do this in Java, please tell me the answer" is not.
MatrixFrog
A: 

a for loop that calls substring(start, end) on the input string where the start is what you are incrementing in the for loop and the end is 3 greater than that, and .equals with an if/else-if construct should do what you need.

TofuBeer