Social Icons

Monday, May 17, 2010

notReplace : Solutions for Javabat:20



Given a string, return a string where every appearance of the lowercase word "is" has been replaced with "is not". The word "is" should not be immediately preceded or followed by a letter -- so for example the "is" in "this" does not count. (Note: Character.isLetter(char) tests if a char is a letter.)

notReplace("is test") → "is not test"
notReplace("is-is") → "is not-is not"
notReplace("This is right") → "This is not right"

Source

Solution:

public String notReplace(String s) {
      String news="";
      if(s.indexOf("is")==-1) return s;
      for(int i=0 , end=0 ; i<s.length()-1;i++){
         i=s.indexOf("is",i);
         if(i==0){
             if(s.length()==2) news= "is not";
             else if(!Character.isLetter(s.charAt(2)))   {
                news= "is not";
                end=i=2;
             }
         }
         else if(i== s.length()-2){
            if(!Character.isLetter(s.charAt(i-1)))
              news+= s.substring(end,i)+"is not";
            else
              news+= s.substring(end);
         }
         else if(i==-1){// no more 'is' s
            news+= s.substring(end);
            break;
         }
         else{
            if(!Character.isLetter(s.charAt(i-1))&& 
                 !Character.isLetter(s.charAt(i+2)))
            {
               news+= s.substring(end,i)+"is not";
               end=i=i+2;
            }
         }
      }
      return news;
}
 
 
Blogger Templates http://slots.to/