Leetcode Java求解Longest Common Prefix

来源:互联网 发布:黄道日与黑道日的算法 编辑:程序博客网 时间:2024/06/18 13:04

题目:Write a function to find the longest common prefix string amongst an array of strings.

题意:写出一个函数,求解一个字符串数组中的最长公共前缀。

示例:{“abcd”,“avf”,“adww”,“awew”} 的最长公共前缀是"a"。

解题思路:

1.若数组长度为0,即数组为空数组,则最长公共前缀是空字符串,即“”;

2.利用Arrays.sort()方法对字符串数组进行排序,则排序后的数组中第一个字符串和最后一个字符串的公共前缀即是该字符串数组的最长公共前缀;

3.将排序后的数组中的第一个字符串作为临时的最长公共前缀,若该临时最长公共前缀在最后一个字符串的位置是0(说明最后一个字符串的前缀是该临时zuicha公共前缀),则第一个字符串即为求解的最长公共前缀,否则将第一个字符串逐次删除最后一个字符元素作为临时的最长公共前缀,再判断该临时最长公共前缀在最后一个字符串的位置是否0,若为0,则返回该临时的最长公共前缀。

java实现代码如下:

import java.util.Arrays;public class LongestCommonPrefix {// 最长公共前缀public static String longestCommonPrefix_2(String[] strs) {if (strs.length == 0) {// 数组长度为0,则返回“”return "";}Arrays.sort(strs);// 对数组进行排序String pre = strs[0];// 初始化:将第一个字符串作为临时的最长公共前缀int last = strs.length - 1;// 最后一个字符串的索引while (strs[last].indexOf(pre) != 0)// 判断临时的最长公共前缀在最后一个字符串的位置是否为0pre = pre.substring(0, pre.length() - 1);// 不为0时,说明临时的最长公共前缀不是最后一个字符串的前缀,并删除临时最长公共前缀的最后一位,继续判断return pre;}public static void main(String[] args) {String[] strs = new String[] { "1aczdd", "12acs", "1acwerd" };Arrays.sort(strs);// 对数组进行排序System.out.println("sorted arrays:");for (int i = 0; i < strs.length; i++) {System.out.println(strs[i]);}System.out.println("longest CommonPrefix : " + longestCommonPrefix_2(strs));}}
原创粉丝点击