• JavaScript查找最长的公共前缀


    给定一个字符串数组,我们必须找到它们之间最长的公共前缀。如果没有前缀,则返回空字符串。

    输入: ["flower","flow","flight"]
    得到的目标值: "fl"
    
    输入: ["dog","racecar","car"]
    得到的目标值: ""
    There is no common prefix among the input strings.

    方法 1:使用排序查找最长的常用前缀。

    这个想法是去的。

    • 根据字符串的长度按升序对字符串进行排序。
    • 然后使用其中最小的,并迭代其中的每个字符,因为max前缀将小于或等于最小的字符串。
    • 在每次迭代中,检查其余单词的前缀是否存在,如果存在,则存储它,否则中断并返回字符串。
    1. const longestCommonPrefix = (strs) => {
    2. //If empty array return empty string
    3. if(strs.length === 0){
    4. return "";
    5. }
    6. //To track the prefix
    7. let lc = "";
    8. //Sort the string in ascending order
    9. strs.sort((a, b) => ('' + a).localeCompare(b));
    10. //Get the smallest string.
    11. let smallest = strs[0];
    12. //so that we have to iterate for it only.
    13. for(let i = 0; i < smallest.length; i++){
    14. //Get the first letter
    15. let current = smallest[i];
    16. //Flag to check if prefix is present in the remaining string
    17. let isPresent = true;
    18. for(let values of strs){
    19. //Break if different letter
    20. if(values[i] !== current){
    21. isPresent = false;
    22. break;
    23. }
    24. }
    25. //Break the loop if no prefix
    26. if(i === 0 && !isPresent){
    27. break;
    28. }
    29. //Add the prefix
    30. lc += isPresent ? current : '';
    31. }
    32. //return the prefix
    33. return lc;
    34. };
    35. console.log(longestCommonPrefix(["flower","flow","flight"]));// 结果"f1"

    时间复杂度:O(nlogn +(n *字符串中最小单词的长度))。
    空间复杂度:O(1)或O(n),如果我们使用不同的排序。


    方法 2:通过从末尾删除字符。

    从概念上讲,这就是它的工作原理。

    • 从数组中获取第一个单词。
    • 迭代数组中的每个单词,并检查它是否不是同一个单词。
    • 然后继续从末尾删除字符,直到找到前缀。
    • 如果没有前缀并且字符串变为空,则中断并返回空字符串。

    1. const longestCommonPrefix = (strs) => {
    2. //If empty array
    3. if(strs.length == 0) {
    4. return "";
    5. }
    6. //Get the first word
    7. let str = strs[0];
    8. //look for prefix in each word
    9. for (const word of strs) {
    10. while (word.indexOf(str) !== 0) {
    11. // remove one character from the end
    12. str = str.substring(0, str.length - 1);
    13. if (str === ""){
    14. break;
    15. }
    16. }
    17. }
    18. return str;
    19. };

    时间复杂度:O(n * 最大字符串的长度)。
    空间复杂度:O(1)。

  • 相关阅读:
    tensorflow模型训练图片
    JS(javascript)面试题 7点一次过 => 必会之八股文
    0基础女生学建模前,先看这篇文章
    搜维尔科技:Varjo在混合现实中驾驶船舶
    刷题考试系统 | 如何快速帮助员工掌握岗位基础知识
    MySQL介绍
    进程信号详解
    如何在Cocos中绘制一面国旗祝祖国生日快乐、繁荣昌盛
    SwiftUI Preview传递参数问题
    多目标应用:基于多目标粒子群优化算法MOPSO求解微电网多目标优化调度(MATLAB代码)
  • 原文地址:https://blog.csdn.net/qq_22182989/article/details/125625053