Social Icons

Monday, June 28, 2010

xyzMiddle : Solutions for Javabat : 27


Given a string, does "xyz" appear in the middle of the string? To define middle, we'll say that the number of chars to the left and right of the "xyz" must differ by at most one. This problem is harder than it looks.

xyzMiddle("AAxyzBB") → true
xyzMiddle("AxyzBB") → true
xyzMiddle("AxyzBBB") → false

Source

Solution.

 

public boolean xyzMiddle(String s) 
{
  int index=0;
  
  for(int i=0;i<s.length();i++)
  {
    index=s.indexOf("xyz",i);
    if(index!=-1)
    {
      
      if(index==0 && Math.abs( index-(s.length()-(index+3)))<=1) 
        return true; 
      else if( Math.abs( index-(s.length()-(index+3)))<=1 && s.charAt(index-1)!='.')
         return true;   
      else   
         i=index+2;
    }
  }
  return false;  
}
 
 
Blogger Templates http://slots.to/