Problem
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string ""
.
Example 1:
1 |
|
Example 2:
1 |
|
Note:
All given inputs are in lowercase letters a-z
.
Explanation
-
We can use the first string in the array as a compare string.
-
Loop through the first string’s character, and loop from the second string to last string, compare the corresponding index character. If all matches, we append that character to a result stringbuilder, and loop from the second character of the first string and repeat. If not match or finish looping, we return the stringbuilder.
-
Another approach is sort the string array, and compare the first and the last string.
Solution 1
1 |
|
Solution 2
1 |
|