Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Example 1: Input: ["flower","flow","flight"] Output: "fl" Example 2: Input: ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings. https://leetcode.com/problems/longest-common-prefix/solution/ Solution 2 以後的還沒看 今天睡覺以前要完成, 以谷歌面試的bar 要求本身, 一題能夠多解的 要多解,分析時空 複雜度, 而後比較trade off, 代碼要求bug free , medium 的題應該在15 分鐘以內寫完 這個題的考點是什麼,突破點在哪, 套路是哪個 Solution 1 : 很像 merge sort 的類型, online 算法 class Solution { public String longestCommonPrefix(String[] strs) { if(strs == null || strs.length == 0) return ""; if(strs.length == 1) return strs[0]; String subRes = commonPrefix(strs[0], strs[1]); for(int i = 2; i < strs.length; i++){ subRes = commonPrefix(subRes, strs[i]); } return subRes; } private String commonPrefix(String subRes, String cur){ StringBuilder sb = new StringBuilder(); for(int i = 0; i < Math.min(subRes.length(), cur.length()); i++){ if(subRes.charAt(i) == cur.charAt(i)){ sb.append(cur.charAt(i)); }else{ break; } } return sb.toString(); } } Solution 2 : class Solution { public String longestCommonPrefix(String[] strs) { if(strs == null || strs.length == 0) return ""; StringBuilder sb = new StringBuilder(); for(int i = 0; i < strs[0].length(); i++){ // going thru every index of the first word , i = 0, 1 char c = strs[0].charAt(i); // c = 'a', 'a' boolean flag = true; for(String word : strs){ // going thru every word and check the char at that certain index // if there is a word whose length is smaller than the current i , break , return the current stringbuilder , else if , the new char is differwent from the char of the first word, break , // if its the same, keep going thru all char at the same index. if boolean is still true // append it if(word.length() <= i || word.charAt(i) != c) flag = false; } if(flag) sb.append(c); // sb = a if(!flag) break; } return sb.toString(); } } follow up: Given a set of keys S = [s1, s2, s3, s4, .. sn], find the longest common prefix among a string q and S. This LCP query will be called frequently. Solution: since p changes all the time, the set S doesn’t change, We can use a trie to store all the words in S, so it’s gonna be a prefix tree Containing all the words from S. So every time when we want to get the common Prefix, we don’t have to go thru every words in s, instead, we can just traverse the Trie tree , it’s more efficient that way The end condition when traversing the trie and the word p is when there is no common char between p and the trie tree && trie tree has more than one child