Last active
February 13, 2019 05:05
-
-
Save kylelong/b5e8be5af551f81296f697b007f08316 to your computer and use it in GitHub Desktop.
Cassido's weekly interview problem (2/10/19)
This file contains hidden or 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
/** | |
* Created by Kyle Long on 2/12/19. | |
*/ | |
public class charsToPalindrome { | |
public static void main(String [] args){ | |
String s = "hi"; //hi -> hih or ihi | |
String s1 = "xx"; //already palindrome | |
String s2 = "race"; //racecar | |
String s3 = "abcdabc"; //not possible to convert into a palindrome | |
System.out.println(makeAPal(s)); | |
System.out.println(makeAPal(s1)); | |
System.out.println(makeAPal(s2)); | |
System.out.println(makeAPal(s3)); | |
} | |
/** | |
* Finds the minimum number of characters to be inserted to | |
* convert it to palindrome. | |
* @param s String to covert to potentially convert to a palindrome | |
* @return num of characters needed to be added to make it a palindrome | |
*/ | |
public static int makeAPal(String s){ | |
//already palindrome | |
if(isPalindrome(s)) return 0; | |
StringBuilder sb = new StringBuilder(s); | |
int count = 0; | |
int offset = (s.length() / 2 % 2) == 0 ? 0: 1; | |
for(int i = (s.length() / 2 ) - offset; i >= 0; i--){ | |
sb.append(s.charAt(i)); | |
count++; | |
if(isPalindrome(sb.toString())){ | |
return count; | |
} | |
} | |
return -1; //not possible | |
} | |
/** | |
* Checks if a string is a palindrome | |
* @param s String to check if it is a palindrome | |
* @return if is a palindrome | |
*/ | |
public static boolean isPalindrome(String s){ | |
char [] arr = s.toCharArray(); | |
int length = arr.length; | |
for(int i = 0; i < length / 2; i++){ | |
if(arr[i] != arr[length - 1 - i]){ | |
return false; | |
} | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment