Last active
February 1, 2021 05:23
-
-
Save mumunuu/b855ab40941259a22cb62f20e0906c60 to your computer and use it in GitHub Desktop.
algorithm(leetcode) Longest Common Prefix
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
func longestCommonPrefix(strs []string) string { | |
if len(strs) == 0 { | |
return "" | |
} | |
sort.Slice(strs, func(i, j int) bool { | |
return len(strs[i]) < len(strs[j]) | |
}) | |
answer := "" | |
for i, v := range strs[0] { | |
stopFlag := false | |
curVal := string(v) //현재 값 | |
for k := 0; k < len(strs); k++ { | |
if string(strs[k][i]) == curVal { | |
continue | |
} else { | |
if i != 0 { | |
//현재 값이랑 다르면, 그 전까지 잘라주고 종료 | |
answer = strs[0][0:i] | |
} | |
stopFlag = true | |
break | |
} | |
} | |
if stopFlag { | |
break | |
} else { | |
answer += curVal | |
} | |
} | |
return answer | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment