14. Longest Common Prefix(最長公共字首) —— Java
阿新 • • 發佈:2018-12-31
Write a function to find the longest common prefix string amongst an array of strings.
Example:
Given ["abc","ab","abcd"], return "ab".
class Solution { public String longestCommonPrefix(String[] strs) { String common = ""; if(strs.length == 0) return ""; else if(strs.length == 1) return strs[0]; else{ common = strs[0]; for(int i=1;i<strs.length;i++){ common = campare(common,strs[i]); } return common; } } public String campare(String com, String s){ String result = ""; char[] cArray = com.toCharArray(); char[] sArray = s.toCharArray(); for(int i=0; i<(cArray.length<=sArray.length?cArray.length:sArray.length); i++){ if(cArray[i] == sArray[i]) result += cArray[i]; else break; } return result; } }