LeetCode算法14:java 最长公共前缀

版权声明:可以转载,请注明链接出处 https://blog.csdn.net/xihuanyuye/article/details/85217662

题目
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。

示例 1:
输入: [“flower”,“flow”,“flight”]
输出: “fl”

示例 2:
输入: [“dog”,“racecar”,“car”]
输出: “”
解释: 输入不存在公共前缀。
说明:
所有输入只包含小写字母 a-z 。

说明
这道题目相对简单,这里采用了将第一单词作为标准,轮流对比的方式解决。

代码

public class _14LongestCommonPrefix{
	
	public String longestCommonPrefix(String[] str){
		
		String commonprefix = "";
		boolean flag = true;
		
		if(str.length == 0) return commonprefix;
			for(int i =0;i<str[0].length();i++){
				
				commonprefix = str[0].substring(0,i+1);
				System.out.println(commonprefix);
				for (int j=0; j<str.length; j++) {
					if (str[j].length()<i+1||commonprefix.equals(str[j].substring(0,i+1))==false) {
						//plus one is get the true length, because i is the point
					 	flag = false;
					 	break;
					 	//break; u should try to find break is just in if or in for_of_j
					}
					}
					
				if (flag == false) {
				 	break;
				}	
				}
		
			if (flag == true) {
			 	return commonprefix;
			}else {
			 	return commonprefix.substring(0,commonprefix.length()-1);
			}
		}
	
	public static void main(String[] arg){
	_14LongestCommonPrefix LongestCommonPrefix = new _14LongestCommonPrefix();
		//String[] list1 = {"c","c"};
		//String[] list1 = {"flower","flow","flight"};
		//String[] list1 = {"flower"};
		//String[] list1 = {""};
		String[] list1 = {};
		//String[] list2 = {"dog","racecar","car"};
		System.out.println(list1);
		System.out.println(LongestCommonPrefix.longestCommonPrefix(list1));
		//System.out.println(LongestCommonPrefix.longestCommonPrefix(list2));
		}
	}

猜你喜欢

转载自blog.csdn.net/xihuanyuye/article/details/85217662