14. 最長公共字首(邏輯)1
阿新 • • 發佈:2020-12-12
技術標籤:LeetCode
編寫一個函式來查詢字串陣列中的最長公共字首。
如果不存在公共字首,返回空字串""。
示例1:
輸入: ["flower","flow","flight"]
輸出: "fl"
示例2:
輸入: ["dog","racecar","car"]
輸出: ""
解釋: 輸入不存在公共字首。
解法一:邏輯咯
class Solution { public String longestCommonPrefix(String[] strs) { if(strs == null || strs.length == 0) return ""; String pre = strs[0]; int i = 1; while (i <= strs.length-1) { while(strs[i].indexOf(pre) != 0) { pre = pre.substring(0,pre.length()-1); } i++; } return pre; } }