編寫一個函數來查找字符串數組中的最長公共前綴:
輸入 : ["abca","abc","abca","abc","abcc"]
返回: "abc"
/** * * @param strs string字符串一維數組 * @return string字符串 */ function longestCommonPrefix( strs ) { // write code here if(strs.length === 0 || strs === null){ return "" } let maxid = strs[0].length-1; for(let i = 1;i<strs.length;i++){ var indx = -1; //下標flag while(indx < maxid && indx < strs[i].length-1){ if(strs[0].charAt(indx +1) === strs[i].charAt(indx+1)){ indx++ }else{ break; } } if(indx === -1){ return "" } maxid = indx; } return strs[0].substring(0,maxid+1); } module.exports = { longestCommonPrefix : longestCommonPrefix };
以第一個str為基准,以此遍歷后面的,找到最大的前綴。