Skip to content

Commit

Permalink
[String] add Solution to Longest Common Prefix
Browse files Browse the repository at this point in the history
  • Loading branch information
Yi Gu committed Jun 5, 2016
1 parent d00f3c2 commit aabbbd5
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions String/LongestCommonPrefix.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Question Link: https://leetcode.com/problems/longest-common-prefix/
* Primary idea: Use the first string as the result at first, trim it while iterating the array
* Time Complexity: O(nm), Space Complexity: O(m), m stands for the length of first string
*/

class LongestCommonPrefix {
func longestCommonPrefix(strs: [String]) -> String {
guard strs.count > 0 else {
return ""
}

var res = [Character](strs[0].characters)

for str in strs {
var strContent = [Character](str.characters)

if res.count > strContent.count {
res = Array(res[0 ..< strContent.count])
}

for i in 0 ..< res.count {
if res[i] != strContent[i] {
res = Array(res[0 ..< i])
break
}
}
}

return String(res)
}
}

0 comments on commit aabbbd5

Please sign in to comment.