Created
September 18, 2018 14:48
-
-
Save frankchang0125/67b1b809577032241bffdec92678f9e3 to your computer and use it in GitHub Desktop.
14. Longest Common Prefix
This file contains hidden or 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
func longestCommonPrefix(strs []string) string { | |
prefix := "" | |
if len(strs) == 0 { | |
return prefix | |
} | |
i := 0 | |
for { | |
currentChar := "" | |
for _, str := range strs { | |
if i > len(str) - 1 { | |
return prefix | |
} | |
if currentChar == "" { | |
currentChar = string(str[i]) | |
} else if string(str[i]) != currentChar { | |
return prefix | |
} | |
} | |
prefix = fmt.Sprintf("%s%s", prefix, currentChar) | |
i++ | |
} | |
return prefix | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment