Skip to content

Instantly share code, notes, and snippets.

@danker
Created November 23, 2010 04:23
Show Gist options
  • Save danker/711243 to your computer and use it in GitHub Desktop.
Save danker/711243 to your computer and use it in GitHub Desktop.
Find common prefix given a list of words
//PROBLEM: Find the common prefix for all input words (i.e. "aa" for the list given below)
def words = ['aaaaaee', 'aaabck', 'aajj', 'aaaabbbcccc']
def letterIdx = 0
def shouldContinue = true
def commonPrefix = new StringBuffer()
while (shouldContinue) {
def currentLetter
words.each {
if (currentLetter != null) {
if (!currentLetter.equals(it.charAt(letterIdx))) {
shouldContinue = false
}
} else {
currentLetter = it.charAt(letterIdx)
}
}
if (shouldContinue) {
commonPrefix << currentLetter
letterIdx++
}
}
println "List of words to match against: $words"
println "Common Prefix: $commonPrefix"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment