Problem:
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
Solution:
public int countYZ(String str) { int len = str.length(); int count = 0; str = str.toLowerCase(); for (int i = 0; i < len; i++) { if (str.charAt(i) == 'y' || str.charAt(i) == 'z') { if (i < len-1 && !Character.isLetter(str.charAt(i+1))) count++; else if (i == len-1) count++; } } return count; }
public int countYZ(String str) {
ReplyDeleteint l= str.length();
int countYZ = 0;
str = (str + " ").toLowerCase();
for (int i = 0; i<=l; i++) {
if ((str.charAt(i) == 'z' || str.charAt(i) == 'y') && !Character.isLetter(str.charAt(i+1))) countYZ ++;
}
return countYZ ;
}
public int countYZ(String str) {
ReplyDeletestr = str.toLowerCase();
String[] wordsSet = str.split("[^a-z]");
int result = 0;
for (String word : wordsSet) {
if (word.endsWith("y") || word.endsWith("z")) {
result++;
}
}
return result;
}
public int countYZ(String str) {
ReplyDeleteint count=0;
str=str.toLowerCase();
for(int i=0;i0 && !Character.isLetter(str.charAt(i))){
if(str.charAt(i-1)=='z' || str.charAt(i-1)=='y'){
count++;
}
count+=0;
}
if(i==str.length()-1 && (str.charAt(i)=='z' || str.charAt(i)=='y')){
count++;
}
}
return count;
}