Title:Write a function to find the longest common prefix string amongst an array of strings.
The first of these solutions:
public class Solution { public String longestcommonprefix (string[] strs) { int strslen=strs.length; if (strslen==0) return ""; String Temp=null; for (int i=0;i<strslen;i++) { StringBuilder sb=new StringBuilder (); if (i==0) { temp=strs[0]; Continue; } int tlen=temp.length (); int ilen=strs[i].length (); int len=0; Len= (Tlen>=ilen) Ilen:tlen; for (int j=0;j<len;j++) { Character C=temp.charat (j); if (!c.equals (Strs[i].charat (j))) { int sblen=sb.length (); if (sblen==0) return ""; break; } else{ Sb.append (c); } } temp=sb.tostring (); } return temp;} }
After thinking, there is no need to introduce StringBuilder, so there is a second solution and more efficient.
Second Solution:
public class Solution { public String longestcommonprefix (string[] strs) { int strslen=strs.length; if (strslen==0) return ""; String Temp=strs[0]; for (int i=1;i<strslen;i++) { int tlen=temp.length (); int ilen=strs[i].length (); int len=0; Len= (Tlen>=ilen) Ilen:tlen; Int J; for (j=0;j<len;j++) { Character C=temp.charat (j); if (!c.equals (Strs[i].charat (j))) {break ; } } Temp=temp.substring (0,J); } return temp;} }
leetcode--longest Common Prefix