Social Icons

Thursday, June 3, 2010

starOut : Solutions for Javabat :23


Question: (Source)

Return a version of the given string, where for every star (*) in the string the star and the chars immediately to its left and right are gone. So "ab*cd" yields "ad" and "ab**cd" also yields "ad".

starOut("ab*cd") → "ad"
starOut("ab**cd") → "ad"
starOut("sm*eilly") → "silly"

Solution

public String starOut(String str) {
  if(str.indexOf("*")==-1) return str; // no stars :(
  String starOut="";
  for(int i=0 , lastI=0 ; i<str.length() ; i++){
             
      if(str.charAt(i)=='*' | i==str.length()-1){ // got a star
          if(i==0){// * @ the begining
              i=this.getI(i,str); lastI=i+1;
          }
          else if(i==str.length()-1) { 
              if(str.charAt(i)=='*')
                 starOut+=str.substring(lastI,i-1);
              else
                 starOut+=str.substring(lastI);
              }
              else {
                 starOut+=str.substring(lastI,i-1); // pre * part stored
                 i=this.getI(i,str); lastI=i+1;
              }
          }
     }
     return starOut;
                
}
int getI(int i , String str){
    // skips any adjacent *s 
    while(++i < str.length() && str.charAt(i)=='*' );
    return i;
}
 
 
Blogger Templates http://slots.to/