Solution:
就是brute force的想法,以第一个字符串为标准,对于每个字符串从第一个字符开始,看看是不是和标准一致,如果不同,则跳出循环返回当前结果,否则继续下一个字符。
时间复杂度应该是O(m*n),m表示字符串的最大长度,n表示字符串的个数,空间复杂度应该是O(m),即字符串的长度.
public class Solution { public String longestCommonPrefix(String[] strs) { if(strs == null || strs.length == 0 || hasEmpty(strs)) //if strs has empty string, return "" return ""; if(strs.length == 1) return strs[0]; String str1 = strs[0]; for (int i = 0; i < str1.length(); i++) { char temp = str1.charAt(i); for (int j = 1; j < strs.length; j++) { if (i > strs[j].length() - 1 || strs[j].charAt(i) != temp) { return str1.substring(0, i); } } } return str1; } public boolean hasEmpty(String[] strs){ for(int i = 0; i < strs.length; i++){ if(strs[i].length() == 0) return true; } return false; } }Or
public class Solution { public String longestCommonPrefix(String[] strs) { StringBuilder res = new StringBuilder(); if(strs == null || strs.length == 0) return res.toString(); int index = 0; boolean isSame = true; while(isSame) { for(int i = 0; i < strs.length; i++) { if(strs[i].length() <= index || strs[i].charAt(index) != strs[0].charAt(index)) { isSame = false; break; } } if(isSame) { res.append(strs[0].charAt(index)); index++; } } return res.toString(); } }
No comments:
Post a Comment