10896 米,哈工程“悟空號”AUV 再創馬裡亞納海溝潛深紀錄
阿新 • • 發佈:2021-11-26
編寫一個函式來查詢字串陣列中的最長公共字首。
如果不存在公共字首,返回空字串""。
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/longest-common-prefix
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
心之所向,素履以往 生如逆旅,一葦以航class Solution { public static String longestCommonPrefix(String[] strs) { if (strs == null || strs.length == 0) { return ""; } String prefix = strs[0]; int length = strs[0].length(); for (int i = 1; i < strs.length; ++i) { prefix = getPrefix(prefix, strs[i]); } return prefix; } private static String getPrefix(String prefix, String str) { int index = 0; while (index < prefix.length() && index < str.length() && str.charAt(index) == prefix.charAt(index)) { index++; } return prefix.substring(0, index); } }