【人生苦短,我學 Python】基礎篇——函式與模組(Day13)
阿新 • • 發佈:2021-02-10
編寫一個函式來查詢字串陣列中的最長公共字首。
如果不存在公共字首,返回空字串""
。
示例 1:
輸入:strs = ["flower","flow","flight"] 輸出:"fl"
示例 2:
輸入:strs = ["dog","racecar","car"] 輸出:"" 解釋:輸入不存在公共字首。
提示:
0 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i]
僅由小寫英文字母組成
import java.util.Stack; public class Solution14 { public String longestCommonPrefix(String[] strs) { if (strs.length == 0) { return ""; } if (strs[0].equals("")) { return ""; } String t = ""; int l = 0; // System.out.println("strs[i]:"+strs[i]); for (int j = 1; j <= strs[0].length(); j++) { int count = 0; t = strs[0].substring(0, j); // System.out.println("t:"+t); for (int i = 0; i < strs.length; i++) { // System.out.println(strs[i].substring(0, t.length())); if (strs[i].length() >= t.length() && strs[i].substring(0, t.length()).equals(t)) { count++; // System.out.println("t:" + t); // System.out.println("count:" + count); // return t.substring(0, t.length() - 1); } if (count == strs.length) { l++; // System.out.println("l:"+l); } } } return strs[0].substring(0, l); } public static void main(String[] args) { Solution14 s = new Solution14(); String[] strs = { "flower", "flower", "flower", "flower" }; System.out.println(s.longestCommonPrefix(strs)); } }