Created
November 23, 2010 04:23
-
-
Save danker/711243 to your computer and use it in GitHub Desktop.
Find common prefix given a list of words
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
//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