Social Icons

Saturday, May 8, 2010

mirrorEnds: solutions for Javabat: 17



Given a string, look for a mirror image (backwards) string at both the beginning and end of the given string. In other words, zero or more characters at the very begining of the given string, and at the very end of the string in reverse order (possibly overlapping). For example, the string "abXYZba" has the mirror end "ab".

mirrorEnds("abXYZba") → "ab"
mirrorEnds("abca") → "a"
mirrorEnds("aba") → "aba"

Source

I used separate method for reverse a given string for it can be reused. one can use StringBuffer or StringBuilder too because those classes have reverse method built in.

public String mirrorEnds(String str) {
  
 String mir="";
 if(str.length()<2) return str;
 int k=1;
   while(str.substring(str.length()-k).equals(this.reverse(str.substring(0,k)))){
      mir=str.substring(0, k);
      k++;
      if(k> str.length()) break; 
      // for overlapping is allowed!
   }
        return mir;
 }
 String reverse(String str){
     String rev="";
     int i=str.length();
     while(--i>=0)
        rev+= str.charAt(i)
        
     return rev;
 }
 

 
 
Blogger Templates http://slots.to/