LeetCode14 最长公共前缀

package easy;

import java.util.Arrays;
import java.util.List;

public class LC_14_longestCommonPrefix {

   public static String longestCommonPrefix(String[] strs) {
	   String temp="";
	   StringBuilder stb=new StringBuilder();
	   for (int i=0;i<strs.length;i++)
	   {
	   	  if (i==0)
	   		  temp=strs[i];
	   	  for (int j=0;j<temp.length() && j<strs[i].length();j++)//找到最长公共字串
	   	  {
	   		  if (temp.charAt(j)==strs[i].charAt(j))
	   			  stb.append(temp.charAt(j));
	   		  else
	   			  break;
	   	  }
	   	  temp=stb.toString();
	   	  stb.delete(0, stb.length());
	   }
	   return temp;
   }
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String[] s1={"flower","flow","flight"};
		String[] s2={"dog","racecar","car"};
		List<String[]> inputs=Arrays.asList(s1,s2);
		for (String[] input :inputs)
		System.out.println(LC_14_longestCommonPrefix.longestCommonPrefix(input));
	}

}

猜你喜欢

转载自blog.csdn.net/mou591744873/article/details/80864668