Loading

14. 最长公共前缀

14. 最长公共前缀

题目:https://leetcode-cn.com/problems/longest-common-prefix/description/

package com.test;

public class Lesson014 {
    public static void main(String[] args) {
        String[] strs = new String[]{};
        String prefix = longestCommonPrefix(strs);
        System.out.println(prefix);
    }

    private static String longestCommonPrefix(String[] strs) {
        if (strs.length == 0) {
            return "";
        }
        // 默认公共前缀是第一个字符串
        String res = strs[0];
        for (int i = 1; i < strs.length; i++) {
            // 获取每个字符串
            String current = strs[i];
            int j = 0;
            // 获取循环的最大数值
            int length = Math.min(res.length(), current.length());
            for (; j < length; j++) {
                String res01 = res.substring(j, j + 1);
                String current01 = current.substring(j, j + 1);
                if (!res01.equals(current01)) {
                    break;
                }
            }
            // 每一次循环修正公共前缀
            res = res.substring(0, j);
        }
        return res;
    }
}

 

posted @ 2018-08-13 14:51  stono  阅读(138)  评论(0编辑  收藏  举报