LeetCode OJ 14Longest Common Prefix

Posted xujian_2014

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode OJ 14Longest Common Prefix相关的知识,希望对你有一定的参考价值。

题目链接:https://leetcode.com/problems/longest-common-prefix/

题目:Write a function to find the longest common prefix string amongst an array of strings.

解题思路:寻找字符串数组的最长公共前缀,将数组的第一个元素作为默认公共前缀,依次与后面的元素进行比较,取其公共部分,比较结束后,剩下的就是该字符串数组的最长公共前缀,示例代码如下:

public class Solution 

	public String longestCommonPrefix(String[] strs)
	
		if (strs == null || strs.length == 0)
		
			return "";
		
		String prefix = strs[0];
		for (int i = 1; i < strs.length; i++)
		
			int j = 0;
			while (j < strs[i].length() && j < prefix.length() && strs[i].charAt(j) == prefix.charAt(j))
			
				j++;
			
			if (j == 0)
			
				return "";
			
			prefix = prefix.substring(0, j);
		
		return prefix;
	


以上是关于LeetCode OJ 14Longest Common Prefix的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode OJ 5 Longest Palindromic Substring

#Leetcode# 14. Longest Common Prefix

Longest Substring Without Repeating Characters -- LeetCode

leetcode14. longest common prefix

Leetcode 14. Longest Common Prefix

LeetCode:14. Longest Commen Prefix(Easy)