'Given a string, count the number of words ending in 'y' or 'z'

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.)

For example,

    countYZ("fez day") → 2
    countYZ("day fez") → 2
    countYZ("day fyyyz") → 2
    countYZ("day yak") → 1  
    countYZ("day:yak") → 1      
    countYZ("!!day--yaz!!") → 2 

But I'm failing these cases:

countYZ("fez day") → should be 2 but Im getting 1           
countYZ("day fez") → should be 2 but Im getting 1    
countYZ("day fyyyz") → should be 2 but Im getting 1

Could smb take a look and see whats wrong with my code? THanks in advance!

public int countYZ(String str) {

  int count = 0;
  for(int i = 0; i < str.length()-1; i++){
    if((str.charAt(i) == 'y' || str.charAt(i) == 'z')
     && !(Character.isLetter(str.charAt(i + 1)))){
        count++;
     } 
  }
  return count;
}


Solution 1:[1]

Since you tagged that question with regex, here's a solution using regular expressions:

public int countYZ(String str) {
    Matcher m = Pattern.compile("[yz]\\b").matcher(str);
    int count = 0;
    while (m.find())
        count++;
    return count;
}

Here, the expression "[yz]\\b" means "y or z, followed by a word boundary", i.e. it matches whenever there is an y or z at the end of a word. Just count the matches.

Solution 2:[2]

This code works for this task:

public int countYZ(String str) {
      int counter;
      String regex = "[YyZz](?!\\p{IsAlphabetic})"; 
      java.util.regex.Pattern yzEnd = java.util.regex.Pattern.compile(regex);
      java.util.regex.Matcher matcher = yzEnd.matcher(str);
      for (counter = 0; matcher.find(); counter++);
      return counter;
      
}

p{IsAlphabetic} matches the characters p{IsAlphabetic} literally (case sensitive)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tobias_k
Solution 2 Eugene Khlebnikov