【LeetCode OJ 14】Longest 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;
	}
}


posted @ 2017-06-19 15:11  brucemengbm  阅读(110)  评论(0编辑  收藏  举报