题目
分析
两两比较
代码实现
package com.ccy.test; public class Test33 { public static void main(String[] args) { String[] strs={"dog","racecar","car"}; String res=longestCommonPrefix(strs); System.out.println(res); } public static String longestCommonPrefix(String[] strs) { String temp=strs[0]; for(int i=1;i<strs.length;i++) { temp=f(strs[i],temp); } return temp; } public static String f(String str1,String str2) { StringBuilder sb=new StringBuilder(); int len=str1.length()<str2.length()?str1.length():str2.length(); for(int i=0;i<len;i++) { if(str1.charAt(i)==str2.charAt(i)) { sb.append(str1.charAt(i)); }else { break; } } return sb.toString(); } }
学习情况
1次