LeetCode 14 Longest Common Prefix 最长前缀

来源:互联网 发布:温州平阳网络问政平台 编辑:程序博客网 时间:2024/06/04 19:19

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

0 0
原创粉丝点击