package com.zmz.algorithm.string;

import com.sun.org.apache.xpath.internal.operations.Bool;

/**
 * @author 张明泽
 * Create by 2022/5/21 10:42
 * 最长公共前缀
 * LeetCode-14
 */
public class LongestPublicPrefix {
    public static void main(String[] args) {
        String[] strs = {"flower","flow","floight"};
        String res = result(strs);
        System.out.println(res);
    }
    public static String result(String[] strs) {
        String preString = strs[0];
        for (int i = 1; i < strs.length; i++) {
            Integer shortString = Math.min(preString.length(),strs[i].length());
            Integer index = 0;
            for (int j = 0; j < shortString; j++) {
                if(preString.charAt(j) != strs[i].charAt(j)) {
                    break;
                }
                index++;
            }
            // 只能更短 不能更长
            preString = preString.substring(0,index);
        }
        if(preString.length() == 0) return "";
        return preString;
    }
}
最后修改:2022 年 05 月 27 日 07 : 11 AM
赏杯咖啡喝 谢谢您~