查找字符串数组中的最长公共前缀

查找字符串数组中的最长公共前缀

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>Documenttitle>
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>

你可能感兴趣的:(查找字符串数组中的最长公共前缀)