LeetCode_字符串_简单_14.最长公共前缀

/**
 * @author wx
 * @description 最长公共前缀
 * @create 2023/12/25
 **/
public class LongestCommonPrefix {
    public static void main(String[] args) {
        String[] arr = new String[]{"flower", "flow", "flight"};
        System.out.println(longestCommonPrefix(arr));

    }

    public static String longestCommonPrefix(String[] arr) {
        String str = arr[0];
        for (int i = 0; i < arr.length; i++) {
            while (!arr[i].startsWith(str)) {
                str = str.substring(0, str.length() - 1);

            }
        }
        return str;
    }
}

你可能感兴趣的:(数据结构和算法,算法,开发语言,java)