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

leetcode--Longest Common Prefix

时间:2014-06-25 17:03:03      阅读:331      评论:0      收藏:0      [点我收藏+]

标签:class   blog   code   java   com   string   

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

public class Solution {
    public String longestCommonPrefix(String[] strs) {
        String prefix = "";
		int length = strs.length;
		if(length > 0){
			prefix = strs[0];
			int prefixLength = strs[0].length();
			for(int i = 1; i < length; ++i){
				int k = 0;
				int strLength = strs[i].length();
				for(int j = 0; j < Math.min(prefixLength, strLength); ++j){
					if(prefix.charAt(j) == strs[i].charAt(j))
						++k;
					else
						break;
				}
				prefix = strs[i].substring(0, k);
				prefixLength = k;
	            if( k == 0)
	                break;
			}
		}
		return prefix;  
    }
}

  

leetcode--Longest Common Prefix,布布扣,bubuko.com

leetcode--Longest Common Prefix

标签:class   blog   code   java   com   string   

原文地址:http://www.cnblogs.com/averillzheng/p/3806156.html

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