Social Icons

Monday, June 7, 2010

zipZap: Solutions for Javabat :24


Question:

Look for patterns like "zip" and "zap" in the string -- length-3, starting with 'z' and ending with 'p'. Return a string where for all such words, the middle letter is gone, so "zipXzap" yields "zpXzp".

zipZap("zipXzap") → "zpXzp"
zipZap("zopzop") → "zpzp"
zipZap("zzzopzop") → "zzzpzp"

Source

Solution

public String zipZap(String str) {
  String s="";
 
  int index=0 ; 
  
  for(int i=0;i<str.length();i++){
     index=str.indexOf("z",i);
     if(index!=-1 && index<str.length()-2 && str.charAt(index+2)=='p'){
       //we got a z*p , remove the middle letter
       s+=str.substring(i,index+1)+str.charAt(index+2);
       i=index+2;
       continue;
     }
     else
        s+=str.substring(i,i+1);
     
  }
    
  return s;
}
 
 
Blogger Templates http://slots.to/