I need to write a static function int count Google Product(String), which returns the product of the number of letters "o" in all the words "google", "gooogle", ... in a string.
- P38.countGoogleProduct("google gooogle") == 6
- P38.countGoogleProduct("google gogle gooogle gooogle") == 18 == 233
- P38.countGoogleProduct("microsoft gogle") == 1
- P38.countGoogleProduct("microsoft amazon facebooooook") == 1
- P38.countGoogleProduct("googleing") == 1
- P38.countGoogleProduct("googlee") == 1
- P38.countGoogleProduct(" google google ") == 4 == 2*2
- P38.countGoogleProduct("googlegoogle") == 1
The answer is guaranteed to be no more than 2*10^9.
This is my code:
import java.util.*;
import java.util.regex.*;
public class P38 {
static int countGoogleProduct(String s) {
boolean f = false;
Pattern p = Pattern.compile("(( +goo+gle +)+( +goo+gle +))|( +goo+gle +)|(.*( +goo+gle +).*)");
Matcher m = p.matcher(s);
if (m.matches()) {
f = true;
} else {
f = false;
}
if (f) {
int c = 1;
boolean g = false;
String ns = new String();
Pattern np = Pattern.compile("o+");
Matcher nm = np.matcher(s);
while (nm.find()) {
ns = nm.group();
c = c * ns.length();
}
return c;
} else {
return 1;
}
}
public static void main(String[] args) {
String s = new String("...");
System.out.println(countGoogleProduct(s));
}
}
But it doesn't work on some tests like " googlegoogle google " == 8 (right anwer 2) "googlegoogle google" == 1 (right anwer 2) Could you tell me how can I fix this?