LeetCode 14. Longest Common Prefix--字符串数组元素的最长公共前缀

来源:互联网 发布:淘宝商城品牌正品40岁 编辑:程序博客网 时间:2024/05/18 02:02

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

"abcdefg"
"abcdefghijk"
"abcdfghijk"
"abcef"
上面的字符串数组的最长公共前缀就是"abc"。

import java.util.Arrays;public class Main {    public String longestCommonPrefix(String[] strs) {        //只用排序之后的,第一个与最后一个字符串比较        if (strs == null || strs.length == 0) {            return "";        }        String result = "";        Arrays.sort(strs);        int size = strs.length;        int n = strs[0].length();        int m = strs[size - 1].length();        for (int i = 0; i < n; i++) {            if (m > i && strs[0].charAt(i) == strs[size - 1].charAt(i)) {                result += strs[0].charAt(i);            } else {                break;            }        }        return result;    }//longestCommonPrefix    public static void main(String[] args) {        System.out.println(new Main().longestCommonPrefix(new String[]{"abcdaaaaaa", "abcdes", "abcde"}));    }}














阅读全文
0 0
原创粉丝点击