Tutorial :Validating nested string in java



Question:

Hi what is the best way to validate a nested string in java?

sample valid string is [aaaa{bbb}] while [{ss]} is not.

Thanks!


Solution:1

I'd use a stack. Iterate over the characters in the string, and every time I see an opening brace, I'd push the corresponding closing brace onto the stack. Every time I see a closing brace, I check to see if it matches the top of the stack. If so, I pop the character from the stack and keep going. Otherwise, it's an invalid string.


Solution:2

Split the string by "{" and "}", while pushing the tokens to a stack. See if everything checks out by the time you reach the last "}".


Solution:3

You have to be a bit more specific than that, I'm afraid. If you're just looking for a certain substring, there's String.contains(), if you want to validate something like "aaabbb cccddd eeefff" where you have to check if there's exactly three letters of each, then it's a job for regular expressions.


Solution:4

I like the stack answer, but depending on the rules for valid strings, that may get complicated. If you can construct a grammar to describe valid strings, you could probably generate a parser using something like ANTLR.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »