LeetCode演算法14:java 最長公共字首
阿新 • • 發佈:2018-12-25
題目
編寫一個函式來查詢字串陣列中的最長公共字首。
如果不存在公共字首,返回空字串 “”。
示例 1:
輸入: [“flower”,“flow”,“flight”]
輸出: “fl”
示例 2:
輸入: [“dog”,“racecar”,“car”]
輸出: “”
解釋: 輸入不存在公共字首。
說明:
所有輸入只包含小寫字母 a-z 。
說明
這道題目相對簡單,這裡採用了將第一單詞作為標準,輪流對比的方式解決。
程式碼
public class _14LongestCommonPrefix{ public String longestCommonPrefix(String[] str){ String commonprefix = ""; boolean flag = true; if(str.length == 0) return commonprefix; for(int i =0;i<str[0].length();i++){ commonprefix = str[0].substring(0,i+1); System.out.println(commonprefix); for (int j=0; j<str.length; j++) { if (str[j].length()<i+1||commonprefix.equals(str[j].substring(0,i+1))==false) { //plus one is get the true length, because i is the point flag = false; break; //break; u should try to find break is just in if or in for_of_j } } if (flag == false) { break; } } if (flag == true) { return commonprefix; }else { return commonprefix.substring(0,commonprefix.length()-1); } } public static void main(String[] arg){ _14LongestCommonPrefix LongestCommonPrefix = new _14LongestCommonPrefix(); //String[] list1 = {"c","c"}; //String[] list1 = {"flower","flow","flight"}; //String[] list1 = {"flower"}; //String[] list1 = {""}; String[] list1 = {}; //String[] list2 = {"dog","racecar","car"}; System.out.println(list1); System.out.println(LongestCommonPrefix.longestCommonPrefix(list1)); //System.out.println(LongestCommonPrefix.longestCommonPrefix(list2)); } }