1

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?

sepp2k
  • 363,768
  • 54
  • 674
  • 675
top secret
  • 45
  • 2
  • 9
  • so if i can understand you are using just a and b what about c d e? – Youcef LAIDANI May 05 '17 at 09:12
  • "_How this can be implemented in Java?_" This is a bit light, have you tried something ? We usually don't implements a solution from scratch. – AxelH May 05 '17 at 09:17
  • This question may help : http://stackoverflow.com/questions/3763970/find-occurrences-of-characters-in-a-java-string – Arnaud May 05 '17 at 09:22
  • I don't know java programming, but I find it ridiculous that people try to use regexes and what not to solve a simple counting problem for anon-regular expression. – MikeMB May 05 '17 at 12:24

3 Answers3

1

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 as) to make it work for the current scenario.

Java test:

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
Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

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));  
Eritrean
  • 15,851
  • 3
  • 22
  • 28
0

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 :

  1. replace the ab with a-b
  2. split with -, the result should look like [aaaa, bb]
  3. test if the spl[0] contain only a and spl[1] contain only b if yes compare between the spl[0] and spl[1] lenght

Ideone demo

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140