Task from Codingbat :
Given a string, count the number of words ending in 'y' or 'z' -- so the 'y' in "heavy" and the 'z' in "fez" count, but not the 'y' in "yellow" (not case sensitive). We'll say that a y or z is at the end of a word if there is not an alphabetic letter immediately following it. (Note: Character.isLetter(char)
tests if a char is an alphabetic letter.)
countYZ("fez day") → 2
countYZ("day fez") → 2
countYZ("day fyyyz") → 2
I'm trying to solve this task like this:
public int countYZ(String str) {
String regex = "(.[.^y^z]\\b)";
return str.toLowerCase().replaceAll(regex, "").length();
}
But not all the tests were passed. How can I fix regex = "(.[.^y^z]\b)" in order to pass all the tests?
CodePudding user response:
Better to restrict using regex where you can do so. You can make the solution like this:
public static int countYZ(String str) {
String[] strings = str.toLowerCase().split("\\s");
int n = 0;
for (String s : strings) {
if (s.endsWith("y") || s.endsWith("z")) {
n ;
}
}
return n;
}
CodePudding user response:
You could capture either y or z in a capture group not followed by a char a-z, and match any other char.
In the replacement use capture group 1.
([yYzZ](?![A-Za-z]))|.
Explanation
(
Capture group 1[yYzZ]
Match y or z in lower or uppercase(?![A-Za-z])
Negative lookahead, assert not a char A-Za-z directly to the right
)
Close group 1|
Or.
Match any other character
See a regex demo and a Java demo.
Example
public int countYZ(String str) {
String regex = "([yYzZ](?![A-Za-z]))|.";
return str.toLowerCase().replaceAll(regex, "$1").length();
}