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
  • 353,842
  • 52
  • 662
  • 667
top secret
  • 45
  • 2
  • 9
  • so if i can understand you are using just a and b what about c d e? – YCF_L 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
  • 561,645
  • 34
  • 376
  • 476
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
  • 13,003
  • 2
  • 20
  • 25
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

YCF_L
  • 51,266
  • 13
  • 85
  • 129
  • 1
    yes it work a mistake i was checking with spl[0] and spl[0] i edit it just right now @SanketMakani – YCF_L May 05 '17 at 09:48