LeetCode-014-最長公共字首
阿新 • • 發佈:2021-06-19
最長公共字首
題目描述:編寫一個函式來查詢字串陣列中的最長公共字首。
如果不存在公共字首,返回空字串 ""。
示例說明請見LeetCode官網。
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/longest-common-prefix/
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
解法一:字元陣列法
把第一個字串放到字元陣列chars中,從第二個字串開始,挨個字元遍歷比較,得到每次不相等的索引位置p,如果p-1小於0,則表示沒有公共字首;遍歷後面的字串,重複這一過程。 中間只要p-1小於0,直接返回空字串,沒有公共字首。 遍歷結束後,獲取chars陣列中從0到p-1位置的字元,返回即為最長公共字首。
public class Solution { public static String longestCommonPrefix(String[] strs) { if (strs == null || strs.length == 0 || strs[0] == null || strs[0].length() == 0) { return ""; } char[] chars = strs[0].toCharArray(); int maxIndex = strs[0].length() - 1; for (int i = 1; i < strs.length && maxIndex >= 0; i++) { String curStr = strs[i]; if (curStr == null || curStr.length() == 0) { return ""; } int curMax = maxIndex; for (int j = 0; j < curStr.length() && j <= curMax && maxIndex >= 0; j++) { if (curStr.charAt(j) != chars[j]) { maxIndex = j - 1; break; } else { maxIndex = j; } } } if (maxIndex < 0) { return ""; } StringBuilder result = new StringBuilder(); for (int i = 0; i <= maxIndex; i++) { result.append(chars[i]); } return result.toString(); } public static void main(String[] args) { System.out.println(longestCommonPrefix(new String[]{"flower", "flow", "flight"})); System.out.println(longestCommonPrefix(new String[]{"ab", "a"})); } }