Longest Common Prefix total accepted:47436 Total submissions:182575
Write a function to find the longest common prefix (prefix) string amongst an array of strings.
Hide Tages String
Translate: Write a function to find the longest common prefix character in a string array
Try one (fail) with the following code:
public static string longestCommonPrefix1 (string[] strs) {//temp is the intermediate amount of String temp=strs[0];if (strs==null| | strs.length==0) {return "";} for (int i = 0, i < strs.length; i++) {for (int j = i; J < Strs.length; J + +) {if (Strs[i].charat (0)!=strs[j].charat (0)) {return "";}}} for (int i = 1; i < strs.length; i++) {int len=temp.length () <strs[i].length () strs[0].length (): Strs[i].length (); int j;for (j = 0; j<len; j + +) {char First=temp.charat (j); Char Current=strs[i].charat (j); if (first!=current) {break;}} Temp=strs[0].substring (0,J);} return temp;}
Try two (success), the code is as follows:
public static String Longestcommonprefix (string[] strs) { int len = strs.length; if (len = = 0) return ""; if (len = = 1) return strs[0]; int i = 1; String temp = strs[0]; while (I < len) { int minlen = Math.min (Temp.length (), strs[i].length ()); if (Minlen = = 0) return ""; int j = 0; while (J < Minlen) { if (Temp.charat (j) = = Strs[i].charat (j)) {J + +; } else { if (j = = 0) temp = ""; break; } } temp = temp.substring (0,j); i++; } return temp;}
Experience: Try one and try to solve the problem of the idea is the same, but try to avoid some general test input, such as: {a,b,c}, which I used two for loop to do the traversal to exclude, too cumbersome. {"", "" "" "} Three empty strings, failed to exclude, then use the method of two attempts to successfully avoid some accidental input.
Idea: Use the intermediate variable temp to make a sub of the public string that appears, which is extracted. Then loop through the loops in turn.
Leetcode longest Common Prefix 14