`
huntfor
  • 浏览: 195347 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

[leetcode]Longest Common Prefix

 
阅读更多

新博文地址:[leetcode]Longest Common Prefix

http://oj.leetcode.com/problems/longest-common-prefix/

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

 其实木有必要求出数组最短字符串的长度的,加一个判断即可

public String longestCommonPrefix(String[] strs){
		if(strs == null || strs.length == 0){
			return "";
		}
		StringBuilder sb = new StringBuilder();
		//------------get shortestLength of strs thus, longest prefix
		int shortestLength = Integer.MAX_VALUE;
		for(String tem : strs){
			if(tem.length()< shortestLength){
				shortestLength = tem.length();
			}
		}

	breakable:	for(int i = 0; i < shortestLength; i++){
			char tem = strs[0].charAt(i);
			for(int j = 1; j < strs.length; j++){
				if(strs[j].charAt(i)!=tem){
					break breakable;
				}
			}
			sb.append(tem+"");
		}

		return sb.toString();

	}

 

分享到:
评论
1 楼 249326109 2014-06-24  
竟然搜到这里了!

相关推荐

Global site tag (gtag.js) - Google Analytics