LeetCode: Longest Common Prefix

Table of contents

topic

example

train of thought

the code

appendix


topic

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

Returns the empty string "" if no common prefix exists.

example

Example 1:

Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: No common prefix exists for the inputs.

train of thought

When scanning vertically, traverse each column of all character strings from front to back, and compare whether the characters on the same column are the same. If they are the same, continue to compare the next column. If they are not the same, the current column no longer belongs to the common prefix. part is the longest common prefix.

In the vertical comparison method, the first one is used as the benchmark, and subsequent elements are compared in turn. Note that when the length of the subsequent element is insufficient, the previous result string will be returned immediately

the code

func longestCommonPrefix(strs []string) string {
	if len(strs) <=0 {
		return ""
	}
	for i:=0;i<len(strs[0]);i++{
		for j:=1;j<len(strs);j++{
			if i == len(strs[j]) || strs[j][i] != strs[0][i]{
				return strs[0][:i]
			}
		}
	}
	return strs[0]
}

appendix

take notes

Guess you like

Origin blog.csdn.net/qq_34417408/article/details/125070218