Original address: leetcode-cn.com/problems/lo…

Topic describes

Analysis of the topic

The most intuitive sense of this problem is:

  • Find the first stringtarget
  • Perform a horizontal scan by column

My code is as follows:

/** * @param {string[]} strs * @return {string} */
var longestCommonPrefix = function(strs) {
    if(! strs || ! strs.length) {return ' '
    }
    let target = strs[0]
    for (let i = 0; i < target.length; i++) {
        for (let j = 1; j < strs.length; j++) {
            if(strs[j][i] ! == target[i]) {return i > 0 ? target.slice(0, i) : ' '}}}return target
};
Copy the code
  • Time complexity:O(s).s = m + n(S is the total length of the string)
  • Space complexity:O(1)

Of course, there are other solutions to this problem, such as dichotomy and divide and conquer. The official solution has been written very carefully, so I will not repeat it here.

Write in the last

I have been brushing questions on LeetCode and joined the organization before. If you are interested in learning together, you can leave a message below or follow my wechat public account “Tony’s Front-end Cram School” and leave a message in the background. You can join the group to learn with the big guys.