[Algorithm -- LeetCode] (14) Longest common prefix

insert image description here

1. 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 1:

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

Example 2:

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

Topic link: https://leetcode.cn/problems/longest-common-prefix

2. Diagram

If we want to find the longest common prefix, then first of all, this prefix is ​​public, and we can find it from any element. Assuming that we are now looking for the longest common prefix from an array, first of all, we can set the first element as the reference element x0. If the array is ["flow", "flower", "flight"], flow is our reference element x0.

Then we only need to compare the reference element with the following elements in turn (assuming that the following elements are x1, x2, x3...), and constantly update the reference element until the reference element and all elements meet the condition of the longest common prefix . The longest common prefix can be obtained.

The specific comparison process is as follows:

  • If strings.Index(x1,x) == 0, skip directly (because x is the longest common prefix of x1 at this time), and compare the next element. (such as flower and flow for comparison)
  • If strings.Index(x1,x) != 0, then intercept the last element of the reference element x, and compare it with x1 again until string.Index(x1,x) == 0, then the intercepted x is the longest common prefix of x and x1. (For example, compare flight and flow, intercept flow-flo-fl in sequence until fl is intercepted, at this time fl is the longest common prefix of flight and flow)

The specific process is shown in the figure below:
insert image description here
Note: In the process of processing the reference element, if the reference element cannot match any element, it means that there is no longest common element.

Finally, we remember to handle critical conditions. If the given array is empty, it also means that there is no longest common element.

3. Java sample code

class Solution {
    
    
    public String longestCommonPrefix(String[] strs) {
    
    
        if (strs.length == 0 || strs == null) {
    
    
            return "";
        }
        String ans = strs[0];
        for (int i = 1; i < strs.length; i++) {
    
    
            int j = 0;
            for (; j < ans.length() && j < strs[i].length(); j++) {
    
    
                if (ans.charAt(j) != strs[i].charAt(j)) {
    
    
                    break;
                }
            }
            ans = ans.substring(0, j);
            //不存在公共前缀
            if (ans.equals("")) {
    
    
                return "";
            }
        }
        return ans;
    }
}

Results of the:
insert image description here

Guess you like

Origin blog.csdn.net/duoduo_11011/article/details/131592915