Created
March 5, 2013 15:50
-
-
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")…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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