Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Palindrom
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
You can’t perform that action at this time.