Skip to content

Instantly share code, notes, and snippets.

@sinanduman
Created March 5, 2013 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sinanduman/5091242 to your computer and use it in GitHub Desktop.
Save sinanduman/5091242 to your computer and use it in GitHub Desktop.
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")…
package teach;
public class MirrorsEnd {
/**
* @param args
*/
public static void main(String[] args) {
String[] words = { "abXYZba", "abca", "aba", "Hi and iH", "123and then 321" };
for (int i = 0; i < words.length; i++) {
System.out.println(words[i] + " => " + mirrorEnds(words[i]));
}
}
public static String mirrorEnds(String temp) {
StringBuilder sb= new StringBuilder("");
boolean diff = false;
for (int i = 0; i < temp.length() / 2 && (!diff); i++) {
if (temp.charAt(i) == temp.charAt((temp.length() - 1) - i)) {
sb.append(temp.charAt(i));
} else {
diff = true;
}
}
if (!diff)
sb = new StringBuilder(temp);
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment