LeetCode 14 Longest Common Prefix (Longest Common Prefix)
Translation
Write a function (or method) to find the longest common prefix in a string array.
Original
Write a function to find the longest common prefix string amongst an array of strings.
Meaning
The longest common prefix of the string array above abcdefgabcdefghijkabcdfghijkabcef is abc.
Thoughts
As shown in, the first step is to find the length and sequence of the shortest string in the string array.
Step 2: Use For Perform the following steps to compare the loop from the first string to the last string:
Outer Layer For In the loop, I is used to represent the string length, from MinSize It can be decreased 0
Initial Result Is the shortest string MinIndex (OK) the first I characters
Inner Layer For In Circulation J The index in the string array. J Equal MinIndex Do not perform the operation (because the same string does not need to be compared)
Otherwise, use a temporary string Temp To get the front of the character whose index is j. I Characters
All Temp Both Result Equal
If J And Len It means that all strings have been traversed.
Each time the string length is reduced, it is updated. Result
Code
public class Solution { public string LongestCommonPrefix(string[] strs) { int len = strs.Length; if(len == 0) return ; string result = ; int minSize = 100000; int minIndex = 0; if(len == 1){ result = strs[0]; return result; } for(int i = 0; i < len; i++){ int size = strs[i].Length; if(size < minSize){ minSize = size; minIndex = i; } } for(int i = minSize; i >= 0; i--){ result = strs[minIndex].Substring(0,i); int j = 0; for(; j < len; j++){ if(j == minIndex) continue; string temp = strs[j].Substring(0,i); if(result != temp) break; } if(j == len) return result; } return result; }