Suppose my program only accepts the strings a^2nb^n
(it can only accept the string with letter "a" repeating twice as amount to letter "b" i.e (aab
, aaaabb
, etc).
How can this be implemented in Java?
Suppose my program only accepts the strings a^2nb^n
(it can only accept the string with letter "a" repeating twice as amount to letter "b" i.e (aab
, aaaabb
, etc).
How can this be implemented in Java?
You may adapt the solution from the How can we match a^n b^n with Java regex?
^(?:aa(?=(?:aa)*(\1?+b)))+\1$
See the regex demo. Here, the a
is replaced with aa
and a*
with (?:aa)*
(a non-capturing group matching 0+ double a
s) to make it work for the current scenario.
List<String> strs = Arrays.asList("ab","aabb","aaaabbbb","aab","aaaabb");
for (String str : strs)
System.out.println(str + ": " + str.matches("(?:aa(?=(?:aa)*(\\1?+b)))+\\1"));
Output:
ab: false
aabb: false
aaaabbbb: false
aab: true
aaaabb: true
The first 2/3 of an accepted string contains "a"´s and the last 1/3 "b"´s. So you can use a regex like "a{x,y}b{x,y}" where x is the min accurance and y the max.
String str = "aaaabb";
int n = str.length();
String regex = "a{"+(n*2/3)+"}b{"+(n/3)+"}";
System.out.println(str.matches(regex));
Here is a simple solution:
String str = "aab";
String spl[] = str.replace("ab", "a-b").split("-");
boolean check = spl[0].matches("a+") && spl[1].matches("b+")
&& spl[0].length() == 2 * spl[1].length();
The result of split is :
[aa, b]
The idea is :
ab
with a-b
-
, the result should look like [aaaa, bb]spl[0]
contain only a and spl[1]
contain only b if yes compare between the spl[0]
and spl[1]
lenght