其他分享
首页 > 其他分享> > 查找字符串数组中的最长公共前缀

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

作者:互联网

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

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

标签:end,前缀,var,length,查找,字符串,return,myarr,first
来源: https://www.cnblogs.com/sugartang/p/12163171.html