Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
题解:
解题思路是,先对整个String数组预处理一下,求一个最小长度(最长前缀肯定不能大于最小长度)。
for each char in the shortest strings (starts from [0] ), if it equal to other string in the array, it is a common prefix, we continue check the next index (e.g., [1] ), if they are the same, we continue check the next (e.g., [2])... The termination conditions is if the chars of same index are not the same, the longest prefix is the sub string from 0 to current index-1.
So the algorithm is pretty simple, scan from the first character of the shortest string, if it is same for all the strings, go to the next character. Return the string until meet the different character.
Last updated
Was this helpful?