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

<!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-07-31 13:59:18

查找字符串数组中的最长公共前缀的相关文章

面试题:编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 &quot;&quot;。(c++实现)

实例说明 示例 1: 输入: ["flower","flow","flight"] 输出: "fl" 示例 2: 输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀. 说明: 所有输入只包含小写字母 a-z . 实现方法: #include<iostream> #include<vec

LeetCode -- 求字符串数组中的最长公共前缀

题目描写叙述: Write a function to find the longest common prefix string amongst an array of strings.就是给定1个字符串数组,找出公共最长前缀. 思路非常直接.使用1个索引来存最长公共前缀的长度就能够了. 注意, 假设使用1个字符串变量来存前缀的话,是不能AC的,由于题目不同意使用额外的空间. public string LongestCommonPrefix(string[] strs) { if(strs

python查找最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀. 如果不存在公共前缀,返回空字符串 "". 示例 1: 输入: ["flower","flow","flight"] 输出: "fl" 示例 2: 输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀. 说明: 所有输入只包含小写字母 a-

【简单算法】20.最长公共前缀

题目: 编写一个函数来查找字符串数组中的最长公共前缀. 如果不存在公共前缀,返回空字符串 "". 示例 1: 输入: ["flower","flow","flight"] 输出: "fl" 示例 2: 输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀. 说明: 所有输入只包含小写字

leetcode 最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀. 如果不存在公共前缀,返回空字符串"". 示例 1: 输入: ["flower","flow","flight"] 输出: "fl" 示例 2: 输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀. 说明: 所有输入只包含小写字母a-z

【leetcode 简单】第五题 最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀. 如果不存在公共前缀,返回空字符串 "". 示例 1: 输入: ["flower","flow","flight"] 输出: "fl" 示例 2: 输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀. 说明: 所有输入只包含小写字母 a-

LeetCode 7最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀. 如果不存在公共前缀,返回空字符串 "". 示例 1: 输入: ["flower","flow","flight"] 输出: "fl" 示例 2: 输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀. 说明: 所有输入只包含小写字母 a-

leetcode 13.最长公共前缀

编写一个函数来查找字符串数组中的最长公共前缀. 如果不存在公共前缀,返回空字符串 "". 1 class Solution: 2 def longestCommonPrefix(self, strs): 3 """ 4 :type strs: List[str] 5 :rtype: str 6 """ 7 if len(strs) == 0: 8 return "" 9 if len(strs) == 1:

Leetcode篇:最长公共前缀

@author: ZZQ @software: PyCharm @file: longestCommonPrefix.py @time: 2018/9/16 17:50 要求:查找字符串数组中的最长公共前缀.如果不存在公共前缀,返回空字符串 "" e.g.: 输入: ["flower","flow","flight"] 输出: "fl" 输入: ["dog","racecar&