This article is participating in the nuggets team number online activity, click to see the dachang spring recruiting positions

I. Title Description:

Leetcode 14. The longest public prefix

Write a function to find the longest public prefix in an array of strings.

Returns the empty string “” if no public prefix exists.

Example 1:

STRS = ["flower","flow","flight"]Copy the code

Example 2:

STRS = ["dog","racecar","car"]Copy the code

Explanation: The input does not have a common prefix.

Tip:

  • 0 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • STRS [I] consists of lowercase letters only

Ii. Analysis of Ideas:

Recursive loop to find the longest public prefix.

AC code

let findCom = function(strs, ind) { if(! strs[0]) return false; let start = strs[0][ind]; for(let i = 0; i < strs.length; i ++) { if(! start || ! strs[i][ind] || (strs[i][ind] ! = start)) { return false; } } return start; } var longestCommonPrefix = function(strs) { let com = ''; let ind = 0; function digui() { let str = findCom(strs, ind); if (! str) { return com; } else { com += str; ind ++; digui(ind); } } digui(); return com; };Copy the code

The execution result

Results: Beat 33.52% of all JavaScript commits with memory consumption of 40.7 MB and 11.16% of all JavaScript commits with execution time of 100 msCopy the code

Iv. Summary:

  • The technique by which a program calls itself is called recursion
  • Recursion must make loop exit conditions, otherwise it is an infinite loop