Lettcode_14_Longest Common Prefix——查找字符串数组中最长公共前缀字符串

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/40555783

Longest Common Prefix

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

算法是自己想的,虽然有点啰嗦,但是肯定是对的。

希望继续努力,不断提高算法的质量。每天都有所进步,加油。   

算法实现代码如下:

	public static String longestCommonPrefix(String[] strs) {
		if (strs.length == 0)
			return "";
		String min = strs[0];
		if (min.length() == 0)
			return "";
		if (strs.length == 1)
			return min;

		for (int i = 1; i < strs.length; i++) {
			if (min.length() > strs[i].length())
				min = strs[i];
		}

		StringBuffer buff = new StringBuffer();
		boolean flag = false;
		for (int i = 0; i < min.length(); i++) {
			char c = min.charAt(i);
			for (int j = 0; j < strs.length; j++) {
				if (strs[j].length() != 0) {
					if (strs[j].charAt(i) == c) {
						flag = true;
						continue;
					} else {
						flag = false;
						return buff.toString();
					}
				}
			}

			if (flag) {
				buff.append(c);
			}
		}
		return buff.toString();
	}


网上公认较好的解题算法如下所示:

public String longestCommonPrefix(String[] strs) {
		if (strs.length == 0)
			return "";
		int size = strs.length;
		int j = 0;
		int minlength = strs[0].length();

		// find the min length of strings
		for (String s : strs) {
			if (s.length() < minlength) {
				minlength = s.length();
			}
		}

		// take substrings, put into a HashSet. if HashSet size >1, reduce the
		// lengh of substrings;
		while (j < minlength) {
			HashSet<String> h = new HashSet<String>();
			for (int i = 0; i < size; i++) {

				h.add(strs[i].substring(0, minlength - j));
				if (h.size() > 1)
					break;

			}
			if (h.size() == 1)
				return strs[0].substring(0, minlength - j);
			j++;

		}
		return "";
	}



你可能感兴趣的:(java,LeetCode,算法,String)