<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <script> var myarr = ["flaaower","flaaow","flaight"] function getLongestCommonPrefix(){ myarr.sort();//按編碼排序 if(myarr.length === 0) return ‘‘; // 如果是空數組直接返回‘‘ var first = myarr[0], end = myarr[myarr.length-1]; if(first === end || end.match(eval(‘/^‘ + first + ‘/‘))){ return first; //first包含于end返回first } for(var i =0;i<first.length;i++){ if(first[i] !== end[i]){ return first.substring(0,i);//匹配失敗時候返回相應字符串 } } } console.log(getLongestCommonPrefix()); //‘fla‘ </script> </body> </html>
原文地址:https://www.cnblogs.com/sugartang/p/12163171.html
时间: 2024-10-07 18:40:15