Created
January 8, 2016 11:29
-
-
Save aesteve/5a7ec0f856c4f27ea7e4 to your computer and use it in GitHub Desktop.
Palindrom
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
CharSequence.metaClass.getLowerStripped = { | |
delegate.toLowerCase().replaceAll(/\s/, '') | |
} | |
def check() { | |
assert !''.palindrom | |
assert !'palindrom'.palindrom | |
assert 'madam'.palindrom | |
assert 'Evil is a name of foeman as I live'.palindrom | |
} | |
// First version : that's cheating | |
CharSequence.metaClass.isPalindrom = { | |
if (delegate.empty) return false | |
delegate.reverse().lowerStripped == delegate.lowerStripped | |
} | |
check() | |
// Second version : meh. Not efficient at all, but more readable ? | |
// (no need to check the whole string, just the first half) | |
CharSequence.metaClass.isPalindrom = { | |
if (delegate.empty) return false | |
boolean palindrom = true | |
String str = delegate.lowerStripped | |
str.eachWithIndex { c, idx -> | |
if (c != str[-idx - 1]) { | |
palindrom = false | |
} | |
} | |
palindrom | |
} | |
check() | |
// Third version, not that much Groovy-ish (for-loop to break) | |
CharSequence.metaClass.isPalindrom = { | |
if (delegate.empty) return false | |
String str = delegate.lowerStripped | |
int len = str.length() | |
for (int i = 0; i < len / 2 ; i++) { | |
if (str[i] != str[-i - 1]) return false | |
} | |
true | |
} | |
check() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment