算法:最长公共前缀解法

在Java项目中直接创建一个类,就可以直接进行解答:
思路:
1.标签:链表
2.当字符串数组长度为 0 时则公共前缀为空,直接返回
3.令最长公共前缀 ans 的值为第一个字符串,进行初始化
4.遍历后面的字符串,依次将其与 ans 进行比较,两两找出公共前缀,最终5.结果即为最长公共前缀
6.如果查找过程中出现了 ans 为空的情况,则公共前缀不存在直接返回
7.时间复杂度:O(s)O(s),s 为所有字符串的长度之和

  public static void main(String[] args) {
        String[] strs = {"leets","leet","leds"};
        String str = find(strs);
        System.out.println(str);
    }
    public static String find(String[] strs){
        if (strs.length == 0) return "";
         String ans = strs[0];
        for (int i = 1;i < strs.length;i ++){
            int j = 0;
            for (;j < ans.length() && j < strs[i].length();j ++) {
                if (ans.charAt(j) != strs[i].charAt(j))
                    break;
            }
                ans = ans.substring(0,j);
                if (ans.equals("")){
                    return ans;
                }
            }
          return ans;

        }

很好的算法哦!

你可能感兴趣的:(算法:最长公共前缀解法)