码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-14 Longest Common Prefix

时间:2015-04-10 22:11:48      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:



问题描述:Write a function to find the longest common prefix stringamongst an array of strings.

问题分析:

代码:

public class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs == null)
			return null;
		if(strs.length < 1)
			return "";
		if(strs.length == 1)
			return strs[0];
		
		StringBuffer result = new StringBuffer();
		int min_length = Integer.MAX_VALUE;
		//找到最短的字符长度
		for(int i = 0; i < strs.length; i++)
		{
			min_length = min_length < strs[i].length() ? min_length : strs[i].length();
		}
		
		char temp_char;
		for(int i = 0; i < min_length; i++)
		{
			temp_char = strs[0].charAt(i);
			for(int j = 1; j < strs.length; j++)
			{
				if(temp_char != strs[j].charAt(i))
					return result.toString();
			}
			result.append(temp_char);
		}
		return result.toString();
    }
}

leetcode-14 Longest Common Prefix

标签:

原文地址:http://blog.csdn.net/woliuyunyicai/article/details/44984505

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!