-
Notifications
You must be signed in to change notification settings - Fork 41
/
14.swift
53 lines (39 loc) · 1.15 KB
/
14.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//
// LongestCommonPrefix.swift
// LongestCommonPrefix
//
// Created by Lex Tang on 5/4/15.
// Copyright (c) 2015 Lex Tang. All rights reserved.
//
/*
Write a function to find the longest common prefix string amongst an array of strings.
@see also: https://github.com/haoel/leetcode/blob/master/algorithms/longestCommonPrefix/longestCommonPrefix.cpp
*/
import Foundation
import XCTest
func longestCommonPrefix(_ list: [String]) -> String? {
var foundWord = ""
var match = false
if list.count == 0 || list[0].isEmpty {
return .none
}
for (i, char) in list[0].enumerated() {
for (_, str) in list.enumerated() {
match = str[i] == char
if !match {
break
}
}
if match {
foundWord.append(char)
}
}
return foundWord.isEmpty ? .none : foundWord
}
class LongestCommonPrefixTest: XCTestCase {
func testLongestCommonPrefix() {
XCTAssertNil(longestCommonPrefix([]), "")
XCTAssertNil(longestCommonPrefix(["a", "b", "c"]), "")
XCTAssertEqual(longestCommonPrefix(["abc", "abb", "abcd"])!, "ab", "")
}
}