Last active
February 6, 2017 15:10
-
-
Save priort/02cdee31ca63ffb3f8f11ba8564d48b8 to your computer and use it in GitHub Desktop.
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
module PalindromeIndex | |
//Hackertank problem | |
//Palindrome Index | |
// Given a string, , of lowercase letters, determine the index of the character whose removal will make a | |
// palindrome. If is already a palindrome or no such character exists, then print . There will always be a | |
// valid solution, and any correct answer is acceptable. For example, if "bcbc", we can either remove 'b' | |
// at index or 'c' at index . | |
// Input Format | |
// The first line contains an integer, , denoting the number of test cases. | |
// Each line of the subsequent lines (where ) describes a test case in the form of a single string, | |
// . | |
// Constraints | |
// All characters are lowercase English letters. | |
// Output Format | |
// Print an integer denoting the zero-indexed position of the character that makes not a palindrome; if is | |
// already a palindrome or no such character exists, print . | |
// Sample Input | |
// 3 | |
// aaab | |
// baa | |
// aaa | |
// Sample Output | |
// 3 | |
// 0 | |
// -1 | |
// Explanation | |
// Test Case 1: "aaab" | |
// Removing 'b' at index results in a palindrome, so we print on a new line. | |
// Test Case 2: "baa" | |
// Removing 'b' at index results in a palindrome, so we print on a new line. | |
// Test Case 3: "aaa" | |
// This string is already a palindrome, so we print ; however, , , and are also all acceptable answers, as | |
// the string will still be a palindrome if any one of the characters at those indices are removed. | |
let isPalindrome' (str: string) = | |
let rec loop i = | |
if i > str.Length/2 then true | |
elif str.[i] <> str.[str.Length - 1 - i] then false | |
else loop (i + 1) | |
loop 0 | |
let isPalindromeFromIndex left right (str: string): bool = | |
isPalindrome' (str.Substring(left, (right - left) + 1)) | |
let removeElementToFormPalindrome' (str: string) = | |
let rec loop i = | |
if i > str.Length/2 then -1 | |
elif str.[i] <> str.[str.Length - 1 - i] && (isPalindromeFromIndex (i+1) (str.Length - 1 - i) str) then i | |
elif str.[i] <> str.[str.Length - 1 - i] && (isPalindromeFromIndex i (str.Length - 2 - i) str) then (str.Length - 1 - i) | |
else loop (i + 1) | |
loop 0 | |
[<EntryPoint>] | |
let main argv = | |
let numStrings = int (System.Console.ReadLine()) | |
[ | |
for i in 1..numStrings do | |
yield System.Console.ReadLine() |> removeElementToFormPalindrome' | |
] | |
|> List.iter (printfn "%A") | |
0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment