Leetcode_14. The longest common prefix (Java solution)

Topic: 14. Longest Common Prefix

Write a function to find the longest common prefix in an array of strings.
If there is no common prefix, an empty string "" is returned.

Example 1:

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

Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix for input.

Speaking in advance, I first used a custom comparison method in the Arrays tool class to sort by the length of the elements in the string array, which greatly reduces the null pointer exception and characters that are raised when judging whether the prefix is ​​the prefix. Abnormal possibility of string subscript out of bounds.
Look at the code directly:

class Solution {
    
    
    public String longestCommonPrefix(String[] strs) {
    
    
     	//默认空字符串数组无公共前缀
		 if(strs.length==0){
    
     return "";}
		 //默认字符串数组只有一个元素时,该元素就是他的公共前缀
	     if(strs.length==1){
    
    return strs[0];}
	     
	     //根据数组中字符串的长度进行排序
		 Arrays.sort(strs, new Comparator<String>() {
    
    
			 @Override
			public int compare(String o1, String o2) {
    
    
				// TODO Auto-generated method stub
				return o1.length()>=o2.length()?1:-1;
			}
		});
		 
		 //创建公共前缀的字符串并赋值为strs数组第一个元素
		 String CommonPrefix=strs[0];
		 
		 //从数组的第二个(即下标为1)元素开始遍历
		for(int i=1,len=strs.length;i<len;i++) {
    
    
			
			//如果该元素只有一个字符,并且与公共前缀CommonPrefix不同,返回空字符串
			 if(strs[i].length()==1 && !CommonPrefix.equals(strs[i])) {
    
    
				 return "";
			 }
			 
			 //判断该元素是否以该公共前缀开始,若不是
			 if(!strs[i].startsWith(CommonPrefix)) {
    
    
			
				 //遍历该元素,至公共前缀的长度
				 for(int k=0;k<CommonPrefix.length();k++) {
    
    
					
					 //判断第k为字符是否与公共前缀第k为相同,若不同
					if(strs[i].charAt(k)!=CommonPrefix.charAt(k)) {
    
    
						
						//截取该元素的前k位传给公共字符串
						CommonPrefix=strs[i].substring(0,k);
					}
				}
			 }	
		}
		//返回公共前缀
		return CommonPrefix;   
	 }
}

Attach a link to the title at the end: 14. The longest common prefix

Guess you like

Origin blog.csdn.net/weixin_51529267/article/details/113482910