[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();

	}

 

你可能感兴趣的:(LeetCode)