Social Icons

Saturday, April 3, 2010

countYZ : Solutions for Javabat: 03


Question:

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

Source:

My Solution:

public int countYZ(String str) {
 int yz=0;
        for(int i=0; i<str.length(); i++){
            
   if(str.charAt(i)=='y' | str.charAt(i)=='z' | str.charAt(i)=='Y'|str.charAt(i)=='Z' ){
                
                if(i==str.length()-1) {yz++; break;}
                if( !Character.isLetter( str.charAt(++i) ) ){ yz++; }
                else {i--;} // next character is a letter
                
            }
           
        }
        return yz;
}
 
 
Blogger Templates http://slots.to/