के बाद से दुनिया जाहिर स्विफ्ट में एक जवाब के लिए भीख माँग रहा है, यहाँ मेरा है;)
func longestCommonPrefix(strings:[String]) -> String {
var commonPrefix = ""
var indices = strings.map { $0.startIndex}
outerLoop:
while true {
var toMatch: Character = "_"
for (whichString, f) in strings.enumerate() {
let cursor = indices[whichString]
if cursor == f.endIndex { break outerLoop }
indices[whichString] = cursor.successor()
if whichString == 0 { toMatch = f[cursor] }
if toMatch != f[cursor] { break outerLoop }
}
commonPrefix.append(toMatch)
}
return commonPrefix
}
स्विफ्ट 3 अद्यतन:
func longestCommonPrefix(strings:[String]) -> String {
var commonPrefix = ""
var indices = strings.map { $0.startIndex}
outerLoop:
while true {
var toMatch: Character = "_"
for (whichString, f) in strings.enumerated() {
let cursor = indices[whichString]
if cursor == f.endIndex { break outerLoop }
indices[whichString] = f.characters.index(after: cursor)
if whichString == 0 { toMatch = f[cursor] }
if toMatch != f[cursor] { break outerLoop }
}
commonPrefix.append(toMatch)
}
return commonPrefix
}
दिलचस्प बात यह है गौर करने योग्य
- यह ओ^2, या ओ (एनएक्सएम) में चलता है जहां एन स्ट्रिंग्स की संख्या है और एम सबसे छोटी की लंबाई है।
- यह स्ट्रिंग.इंडेक्स डेटा प्रकार का उपयोग करता है और इस प्रकार
Grapheme Clusters
से संबंधित है जो Character
प्रकार का प्रतिनिधित्व करता है।
और समारोह मैं पहली जगह में लिखने के लिए की जरूरत को देखते हुए:
/// Takes an array of Strings representing file system objects absolute
/// paths and turn it into a new array with the minimum number of common
/// ancestors, possibly pushing the root of the tree as many level downwards
/// as necessary
///
/// In other words, we compute the longest common prefix and remove it
func reify(fullPaths:[String]) -> [String] {
let lcp = longestCommonPrefix(fullPaths)
return fullPaths.map {
return $0[lcp.endIndex ..< $0.endIndex]
}
}
यहाँ
एक न्यूनतम इकाई परीक्षण है:
func testReifySimple() {
let samplePaths:[String] = [
"/root/some/file"
, "/root/some/other/file"
, "/root/another/file"
, "/root/direct.file"
]
let expectedPaths:[String] = [
"some/file"
, "some/other/file"
, "another/file"
, "direct.file"
]
let reified = PathUtilities().reify(samplePaths)
for (index, expected) in expectedPaths.enumerate(){
XCTAssert(expected == reified[index], "failed match, \(expected) != \(reified[index])")
}
}
@Mark मेरा मानना है कि इस उदाहरण होगा 'flow' । प्रस्तावित समाधान के संदर्भ में निर्णय लेना, यह केवल कम से कम 2 के लिए आम होना चाहिए, सभी के लिए नहीं। मैं सहमत हूं कि ओपी से कुछ स्पष्टीकरण यहां जरूरी है। – corsiKa
एक स्ट्रिंग 'fl' के बिना शुरू हो सकती है। 'हैलो' को एक बिंदु साबित करने के लिए रखा गया था कि यह किसी भी तार हो सकता है जहां 1 स्ट्रिंग में अन्य के साथ कोई सामान्य उपसर्ग नहीं होना चाहिए – shreyasva