`
vvaaiinn
  • 浏览: 20991 次
  • 性别: Icon_minigender_1
  • 来自: 大连
文章分类
社区版块
存档分类
最新评论

LeetCode 14 Longest Common Prefix 最长前缀

阅读更多

题目: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];
	    }

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics