首页 > 学院 > 开发设计 > 正文

leetCode之路——Longest Common Prefix

2019-11-06 06:44:51
字体:
来源:转载
供稿:网友

题目要求:给一个字符数组,求这个数组的最长公共前缀。 思路:首先判断这个字符串数组是否为空,若为空则返回空字符串。然后查找这个字符串数组中最短字符串的长度,之后遍历这个数组,如果这个字符是公共前缀则加入到结果字符串中,继续遍历,否则返回当前结果字符串。 贴上代码:

package leetcode;public class LongestCommonPRefix14 { public static void main(String[] args) { Solution_LCP solu = new Solution_LCP(); String[] strs = {"abca","abc"}; System.out.println(solu.longestCommonPrefix(strs)); }}class Solution_LCP { public String longestCommonPrefix(String[] strs) { int len=strs.length,i=0,min=Integer.MAX_VALUE,j=0; //len为数组长度,i为数组下标,j为数组元素字符串的定位,min为数组中最短的字符串长度 String result="";//result用来接收结果字符串 if(len==0)return result;//如果是空字符数组,则返回空字符串 for(;i<len;i++)//查找字符串数组中最短字符串的长度 { if(strs[i].length()<min)min=strs[i].length(); } //System.out.println("min="+min+" len="+len); while(j<min)//遍历这个字符串 { i=0;//归零 while(i<len-1)//遍历这个字符串数组 { if(strs[i].charAt(j)!=strs[i+1].charAt(j)) return result;//如果有一个不等的字符,则返回result i++; } result+=strs[i].charAt(j);//这个字符是公共前缀,则加入到结果中 //System.out.println(result); j++; } return result; }}

总结:从问题中分析规律,首先要考虑特殊情况,以防止数组越界!


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表