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

Topic describes

Write a function to find the longest public prefix in an array of strings. Returns the empty string “” if no public prefix exists.

For example, STRS = [“flower”,”flow”,”flight”], the longest public prefix is “fl” array [“dog”,”racecar”,”car”], there is no public prefix, the result is “”

Thought analysis

It’s a common prefix. Every string in the array has to start the same, so you can take the first string and compare it to the other strings.

During the comparison, the same prefix is taken, so the comparison starts from the 0th character and the unequal character exits the inner loop. At this time, j is the subscript of the equal character, and the original string is intercepted to obtain the final result. Remember at the very beginning, judge the length of the string.

Const longestCommonPrefix = function (list) {if(list.length === 0){return ""} let STR = list[0] For (let I =1; i < list.length; I ++) {let j = 0 // list[I] traverses for (; j < list[i].length; If (STR [j]! {if (STR [j]! == list[I][j]) {break}} STR = str.string (0, j); } return str }Copy the code

In the official solution, we use horizontal scanning. For each string iterated, the longest public prefix is updated. After iterating all strings, the longest public prefix in the string array is obtained. Java version, the follow-up can try to change js to write.

conclusion

Stick to LeetCode and try to solve the problem by yourself. Your own method may not be the best, fastest and optimal, or there may be more or less problems with your own method. But this is a process of persistence. Every time after finishing, to see the official answer, at first may not be able to understand, until the understanding will suddenly see light.