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.)
Expected result
Code
public int countYZ(String str) {
int amount = 0;
String[] parts =str.split("\\P{Alpha}+");
for (String part : parts) {
if(part.length()>0){
char lastChar = Character.toLowerCase(part.charAt(part.length()-1));
if(lastChar=='y' || lastChar=='z'){
amount++;
}
}
}
return amount;
}
Reference
http://codingbat.com
No comments :
Post a Comment