This article is participating in the “Java Theme Month – Java Brush questions punch card”, see the activity link for details
The article was first published on the public account “Mushroom Can’t Sleep”
1. Title Description
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 1:
Input: STRS = ["dog","racecar","car"] Output: "" Explanation: The input does not have a common prefix.Copy the code
Tip:
- 0 <= strs.length <= 200
- 0 <= strs[i].length <= 200
- STRS [I] consists of lowercase letters only
Ii. Analysis of Ideas:
So this is a fairly simple problem, but one of the longest common prefixes, it must be continuous, and I can’t confuse that. This problem simply iterates, comparing the first two to get the longest prefix, and then comparing the longest prefix to the next string once, selecting the longest prefix each time.
AC code
class Solution { public String longestCommonPrefix(String[] strs) { if (strs == null || strs.length < 1) { return ""; } String prefix = STRS [0]; For (int I = 1; i < strs.length; I ++) {// Take the longest prefix of each string and assign it to prefix = getCommonPrefix(prefix, STRS [I]); If (prefix = = "" | | the prefix. The length () < 1) {/ / either with the longest prefix string matching is less than direct return to break; } } return prefix; } private String getCommonPrefix(String a, String b) {int length = math.min (a.length(), b.length()); int index = 0; while (index < length && a.charAt(index) == b.charAt(index)) { index ++; } return a.substring(0, index); }}Copy the code
Four,
This problem basically iterates through an array of strings, and then matches the longest prefixes one by one.