您的位置:首页 > 其它

LeetCode 14 Longest Common Prefix 最长前缀

2015-04-23 09:33 429 查看
题目:Write a function to find the longest common prefix string amongst an array of strings.

翻译:求一个字符串数组中 共同的最长前缀。

思路:以第一个串为基准,逐个位置遍历,并遍历字符串数组,如果出现某个字符串长度小于当前位置,或者出现当前位置的字符不相同,返回字串strs[0].substring(0,pos);思路很简单。

代码:
public String longestCommonPrefix(String[] strs) {
 	     int count = strs.length;//字符串的个数
	     int pos = 0;//当前指针位置
	     if (count == 0||strs[0].length()==0) //判断空
	    	 return "";
	     for(; pos < strs[0].length();pos++)
	     {
	    	 for(int j = 1; j < count;j++)
	    	 {
	    		 if(strs[j].length()<=pos||strs[0].charAt(pos)!=strs[j].charAt(pos))//超过长度,或者不相等
	    			 return strs[0].substring(0, pos);  		 //返回字串
	    	 }
	     }
	     return strs[0];
	    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: