leetcode刷題 字串公共字首
阿新 • • 發佈:2020-12-10
技術標籤:leetcode刷題leetcode
class Solution { public String longestCommonPrefix(String[] strs) { if(strs == null || strs.length == 0){ return ""; } String prefix = strs[0]; int count = strs.length; for(int i = 1 ; i < count ; i ++) { prefix = getCommonPrefix(prefix, strs[i]);//呼叫兩個字串取最大公共字首的方法 if(prefix.length()==0) break; } return prefix; } public String getCommonPrefix(String s1, String s2) { //大問題化小 String res = ""; int len = Math.min(s1.length(), s2.length()); //確定字串最小長度 for(int index = 0; index < len; index++) { if(s1.charAt(index)==s2.charAt(index)) { res = res + s1.charAt(index); } else break; } return res; } }
這個題挺有意思,最重要的思想是把多個比較變成兩兩比較