Created
September 6, 2017 04:27
-
-
Save courtneyfaulkner/1dc716f34fa9b4e96715fd44bafe2601 to your computer and use it in GitHub Desktop.
[Palindrome] #practice
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
import java.util.regex.Matcher | |
class Palindrome { | |
static void main(String[] args) { | |
def stuff = 'This, stuff ala ffuts, is a sentence to isPalindrome (tacocat)!!ONE!1!' | |
findPalindromes(stuff, true, true) | |
println '==================' | |
findPalindromes(stuff, true, true, true) | |
println '==================' | |
findPalindromes(stuff, false, true) | |
println '==================' | |
findPalindromes(stuff, false, true, true) | |
// println '==================' | |
// findPalindromes(stuff, false, false) | |
println '==================' | |
findPalindromes('whattatoo', true, true, true) | |
println '==================' | |
findPalindromes('tacocat', true, true, true) | |
println '==================' | |
findPalindromes('burgercat', true, true, true) | |
} | |
static void findPalindromes(String full, boolean showLargest, boolean showFalse, boolean excludePunctuation = false) { | |
for (int i = full.length(); i > 2; i--) { | |
boolean canStop | |
for (int j = 0; j <= (full.length() - i); j++) { | |
String fragment = full.substring(j, (i + j)) | |
boolean isPalindrome = isPalindrome(fragment, excludePunctuation) | |
if (isPalindrome) { | |
canStop = true | |
} | |
if (!showFalse || isPalindrome) { | |
println "${sprintf('%02d', i)} | ${sprintf('%02d', j)} | $fragment | palindrome=${isPalindrome}" | |
} | |
} | |
if (canStop && showLargest) break | |
} | |
} | |
static boolean isPalindrome(String fragment, boolean excludePuncuation) { | |
if (excludePuncuation) { | |
Matcher match = fragment =~ /.*\W+.*/ | |
if (match.matches()) return false | |
} | |
int offset = fragment.length() % 2 | |
boolean matches = true | |
for (int i = 0; i < fragment.length() - offset; i++) { | |
if (fragment.charAt(i) != fragment.charAt(fragment.length() - i - 1)) { | |
matches = false | |
break | |
} | |
} | |
matches | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment