Question

I tried to solve the problem below using regular expression, but couldn't (end up using other approach):

http://community.topcoder.com/stat?c=problem_statement&pm=13006&rd=15846

Given a string, you must check if contains the characters C, A and T in this order, and that there's only one occurrence of each. It can be other characters between these characters. Ex:

CTA -> false
XCYAZTX -> true
ACBBAT -> false
CATT -> false
CCAT -> false
CAAT -> false
CAT -> true

So, it would be:

public String getAnswer(String S) {
   if(S.matches("pattern???")) return "Possible";
   return "Impossible";
}

Does someone know a pattern to use and can share please?

Was it helpful?

Solution

You'd use a pattern like this:

^[^CAT]*C[^CAT]*A[^CAT]*T[^CAT]*$

OTHER TIPS

This regex should work for you:

"(?m)^[^CAT]*C[^CAT]*A[^CAT]*T[^CAT]*$"

Working Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top