首页 > 其他 > 详细

leetcode-14 Longest Common Prefix

时间:2015-04-10 22:09:10      阅读:156      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!