leetcode-14. Longest Common Prefix
14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
要求一个字符串数组里面最长公共前缀字符串(数组里面所有字符串)
一开始求成了字符串数组里面最长公共前缀字符串(任意两个字符串)就变成了如下代码
java代码:
public class Solution { public String longestCommonPrefix(String[] strs) { String s=""; int a=0; for(int i=0;i<strs.length-1;i++){ for(int j=i+1;j<strs.length;j++){ int m=0; while(strs[i].charAt(m)==strs[j].charAt(m)&&m<(strs[i].length()-1)&&m<(strs[j].length()-1)){ m++; } if(m>a){ a=m; s=strs[i].substring(0,m+1); } } } return s; } }
符合题意答案:
public class Solution { public String longestCommonPrefix(String[] strs) { if(strs.length==0)return ""; int a=-1; int m=0; while(a<strs[0].length()&&m!=1){ a++; for(int i=0;i<(strs.length-1);i++){ if(a>=strs[i].length()||a>=strs[i+1].length()||strs[i].charAt(a)!=strs[i+1].charAt(a)) { m=1; break; } } } return strs[0].substring(0,a); } }